MatplotlibXBy @CodeWithMunnaX
Catalog
Track: Subplots & Layouts
Layouts12 mins

21. Subplots with plt.subplot()

Comparing disparate metrics (like temperature vs rainfall, or training loss vs validation accuracy) on separate side-by-side subplots prevents scale distortion and clarifies insights.

Mental Model Intuition

Dividing a newspaper page into a grid of columns and story boxes.

Core Concepts & Mechanics

1-Based Subplot IndexingIndexing

`plt.subplot(nrows, ncols, index)` uses 1-based indexing, numbered row-by-row from top-left (1) to bottom-right (nrows * ncols).

In a 2x2 grid: top-left is 1, top-right is 2, bottom-left is 3, bottom-right is 4.
plt.subplot(2, 2, 1) # Top-left plt.subplot(2, 2, 4) # Bottom-right

Common Beginner Mistakes & Pro Fixes

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

Troubleshooting

Quick Lesson Takeaways

  • `plt.subplot(r, c, i)` activates a specific grid slot.
  • Index numbers run 1 to `r*c` in reading order.
  • Always call `plt.tight_layout()` to prevent overlapping subplot labels.
Topic 21 • 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: Create 1x2 Subplots

+50 XP

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

Objective Instructions:

Create 1x2 subplots. In subplot 1 plot `[1, 2, 3]` with title 'Panel 1', and in subplot 2 plot `[3, 2, 1]` with title 'Panel 2'.

Required Keywords:✓ plt.subplot✓ tight_layout
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