Learn how to create multiple plots within a single figure using Matplotlib's subplots, enabling side-by-side or grid-based data visualization.
What it is
A subplot is an individual axes object within a larger figure. The plt.subplots() function creates a grid of these axes, allowing you to plot different datasets or views in separate panels that share the same canvas. This approach is superior to creating separate figures for related visualizations because it maintains consistent styling and allows for easier comparison.
Key terms include Figure (the entire window), Axes (a single plot area), and GridSpec (the layout specification). When you call subplots, you receive references to both the figure and the array of axes objects.
Why it matters
- Comparative Analysis: Place related charts next to each other to spot trends or discrepancies instantly.
- Space Efficiency: Combine multiple small plots into one image file, reducing clutter in reports or dashboards.
- Shared Context: Apply global titles or labels to the figure while keeping specific axis labels local to each subplot.
- Programmatic Control: Iterate over the axes array to apply the same plotting logic to different datasets efficiently.
Syntax or steps
The basic syntax is fig, ax = plt.subplots(nrows, ncols). Here, nrows and ncols define the grid dimensions. If you specify only one dimension, the result might be a single Axes object rather than an array, so it is often safer to use squeeze=False to ensure ax is always a 2D array.
- Import
matplotlib.pyplot. - Call
plt.subplots()with desired rows and columns. - Access specific plots using indexing, e.g.,
ax[0, 1]. - Plot data on the selected axes.
- Display the figure.
Example
import matplotlib.pyplot as plt
import numpy as np
# Generate sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = x**2
y4 = np.sqrt(x)
# Create a 2x2 grid of subplots
fig, ax = plt.subplots(2, 2, figsize=(8, 6))
# Plot on specific axes
ax[0, 0].plot(x, y1, color='blue')
ax[0, 0].set_title('Sine Wave')
ax[0, 1].plot(x, y2, color='red')
ax[0, 1].set_title('Cosine Wave')
ax[1, 0].plot(x, y3, color='green')
ax[1, 0].set_title('Quadratic')
ax[1, 1].plot(x, y4, color='orange')
ax[1, 1].set_title('Square Root')
# Adjust layout to prevent overlap
plt.tight_layout()
plt.show()
In this example, fig controls the overall window, while ax is a 2x2 NumPy array of Axes objects. We access each quadrant via standard array indexing (row, col). plt.tight_layout() automatically adjusts spacing between subplots to ensure titles and labels do not collide.
Common mistakes
- Forgetting Indexing: Calling
ax.plot()whenaxis an array raises an error. You must select a specific subplot first, likeax[0,0].plot(). - Overlapping Labels: Without
plt.tight_layout()or manual spacing adjustments, subplot titles and axis labels often cut off or overlap. - Confusing Figure vs. Axes: Setting a title on the figure (
fig.suptitle()) places it at the top center, whereasax.set_title()places it above a specific subplot. - Hardcoding Indices: In loops, ensure your index calculation matches the flattened array order if iterating linearly.
When to use it
| Method | Best For | Limitation |
|---|---|---|
plt.subplots() | Regular grids (e.g., 2x2, 3x1) where uniformity is key. | Less flexible for irregular layouts. |
plt.subplot2grid() | Complex layouts where one plot spans multiple rows/columns. | More verbose syntax; harder to maintain. |
fig.add_subplot() | Adding plots dynamically one by one. | Does not return an array for easy iteration. |
Practice
Guided Exercise: Create a 1x3 subplot arrangement. Plot three different random distributions (normal, uniform, exponential) using numpy.random. Add a main title "Distribution Comparison" using fig.suptitle().
Challenge: Modify the previous exercise to make the middle plot twice as wide as the others. Hint: Use gridspec_kw={'width_ratios': [1, 2, 1]} inside plt.subplots().
Quick check
Question: How do you access the bottom-right plot in a 3x3 subplot grid?
Answer: Use ax[2, 2], assuming zero-based indexing.
Summary
Subplots allow you to organize multiple visualizations into a single, cohesive figure using a grid system. By leveraging the returned axes array, you can programmatically control each panel, making it essential for comparative data analysis and clean report generation.