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
indexstarts at 1, not 0. - Using an
indexvalue larger thannrows * ncolscauses an error. - Not calling
plt.tight_layout()can cause overlapping labels. - Mixing
plt.subplot()withplt.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
nrowsbyncols. indexcounts from 1 tonrows * 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.