0
0
MatplotlibHow-ToBeginner ยท 3 min read

How to Use plt.subplot in Matplotlib for Multiple Plots

Use plt.subplot(nrows, ncols, index) to create a grid of plots in one figure, where nrows and ncols define the grid size and index selects the active plot. This lets you draw multiple charts side by side or stacked in a single window.
๐Ÿ“

Syntax

The plt.subplot function has this form:

  • nrows: Number of rows in the grid.
  • ncols: Number of columns in the grid.
  • index: Position of the current subplot (starts at 1, counts left to right, top to bottom).

This sets the active plot area where you can draw your chart.

python
plt.subplot(nrows, ncols, index)
๐Ÿ’ป

Example

This example creates a figure with 2 rows and 2 columns of plots, then draws a simple line chart in each subplot.

python
import matplotlib.pyplot as plt

plt.figure(figsize=(8,6))

# First subplot in 2x2 grid
plt.subplot(2, 2, 1)
plt.plot([1, 2, 3], [1, 4, 9])
plt.title('Plot 1')

# Second subplot
plt.subplot(2, 2, 2)
plt.plot([1, 2, 3], [9, 4, 1])
plt.title('Plot 2')

# Third subplot
plt.subplot(2, 2, 3)
plt.plot([1, 2, 3], [2, 3, 2])
plt.title('Plot 3')

# Fourth subplot
plt.subplot(2, 2, 4)
plt.plot([1, 2, 3], [3, 2, 3])
plt.title('Plot 4')

plt.tight_layout()
plt.show()
Output
A window with 4 line plots arranged in a 2x2 grid, each with its own title: Plot 1, Plot 2, Plot 3, Plot 4.
โš ๏ธ

Common Pitfalls

  • Forgetting that index starts at 1, not 0.
  • Using an index value larger than nrows * ncols causes an error.
  • Not calling plt.tight_layout() can cause overlapping labels.
  • Mixing plt.subplot() with plt.subplots() can confuse figure management.
python
import matplotlib.pyplot as plt

plt.figure()

# Wrong: index starts at 0 (this will cause an error)
# plt.subplot(2, 2, 0)

# Correct:
plt.subplot(2, 2, 1)
plt.plot([1, 2, 3], [1, 2, 3])
plt.title('Correct Index')

plt.tight_layout()
plt.show()
Output
A single plot shown without errors, titled 'Correct Index'.
๐Ÿ“Š

Quick Reference

Remember these tips when using plt.subplot:

  • Grid size is nrows by ncols.
  • index counts from 1 to nrows * ncols.
  • Use plt.tight_layout() to avoid overlap.
  • Use plt.subplots() for more control with returned axes objects.
โœ…

Key Takeaways

Use plt.subplot(nrows, ncols, index) to create multiple plots in a grid layout.
Index starts at 1 and counts left to right, top to bottom.
Call plt.tight_layout() to prevent overlapping plot elements.
Avoid using an index outside the grid range to prevent errors.
For more flexibility, consider using plt.subplots() which returns axes objects.