MatplotlibXBy @CodeWithMunnaX
Catalog
Track: Subplots & Layouts
Layouts14 mins

22. Object-Oriented Subplots (plt.subplots)

The `plt.subplots()` function is the modern standard for generating multi-panel layouts. It returns a `Figure` and an array of `Axes` objects, allowing clean vectorized loop operations.

Mental Model Intuition

Receiving a pre-built organizer tray with labelled compartments ready to be filled with data.

Core Concepts & Mechanics

Understanding `axs` Array ShapesArray Shapes

1x1 -> single `Axes` object. 1xN or Nx1 -> 1D array `axs[i]`. NxM -> 2D array `axs[row, col]`.

Use `axs.flat` to iterate through all subplots in a single flat loop regardless of dimensions.
for ax in axs.flat: ax.set_xlabel('Time')

Common Beginner Mistakes & Pro Fixes

Avoid the top errors and bad plotting practices that trip up new Python developers

Troubleshooting

Quick Lesson Takeaways

  • `fig, axs = plt.subplots(r, c)` returns the canvas and an array of axes.
  • Access 2D subplots via `axs[row, col]`.
  • Use `for ax in axs.flat:` to configure common properties across all panels.
Topic 22 • Python IDE
Python 3.12 • Matplotlib
Run Python code to inspect terminal output.

Real-World Datasets (1-Click Switcher)

Switch from abstract numbers to relatable Cricket, Cinema & Business charts

5 Curated Datasets

Hands-on Challenge: Iterate Over 2 Subplots

+50 XP

Write Matplotlib code to solve the objective and see your live plot render

Objective Instructions:

Create `fig, axs = plt.subplots(1, 2)`. In `axs[0]` plot `[1, 2, 3]` and in `axs[1]` plot `[4, 5, 6]` with titles 'A' and 'B'.

Required Keywords:✓ plt.subplots✓ axs
Challenge Code Editor
Challenge Output GraphLive Vector Preview
Write code on the left to render live challenge plot
End of Lesson Knowledge Check

Quick Mini Quiz: 2 Concept Questions

Test your understanding to unlock the lesson completion badge

Q1

Which Matplotlib function is used to create a standard continuous 2D line plot?

Q2

What must you call after specifying label='...' so that the legend actually appears on the canvas?

0 of 2 answered