Subplots put several charts in one figure, so you can compare them side by side. This is standard in data analysis reports and when checking model results.
Prerequisites
A Grid of Charts
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 100)
fig, axes = plt.subplots(2, 2, figsize=(10, 6))
axes[0, 0].plot(x, np.sin(x)); axes[0, 0].set_title('sin')
axes[0, 1].plot(x, np.cos(x), 'r'); axes[0, 1].set_title('cos')
axes[1, 0].bar(['A', 'B', 'C'], [3, 7, 5]); axes[1, 0].set_title('bar')
axes[1, 1].hist(np.random.default_rng(0).normal(size=300), bins=20); axes[1, 1].set_title('hist')
fig.suptitle('Four Charts')
fig.tight_layout()
plt.show()
Explanation: plt.subplots(2, 2) returns the figure and a 2×2 array of axes. axes[row, col] picks one. tight_layout() stops titles overlapping.
One Row of Charts
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4), sharey=True)
ax1.plot([1, 2, 3], [4, 6, 5])
ax2.scatter([1, 2, 3], [5, 3, 6])
plt.show()
Explanation: With one row, axes is 1D and can be unpacked. sharey/sharex give the charts the same scale.
Loop Over Axes
fig, axes = plt.subplots(2, 3, figsize=(12, 6))
for i, ax in enumerate(axes.flat):
ax.plot(np.arange(10) ** (i / 2 + 0.5))
ax.set_title(f'Chart {i + 1}')
fig.tight_layout()
plt.show()
The Older plt.subplot Style
plt.subplot(1, 2, 1)
plt.plot([1, 2, 3])
plt.subplot(1, 2, 2)
plt.plot([3, 2, 1])
plt.show()
Explanation: plt.subplot(rows, cols, index) picks the position (index starts at 1). You will see it in older code; the plt.subplots style above is preferred.
Common Errors
| Problem | Cause and fix |
|---|---|
TypeError: 'Axes' object is not subscriptable |
With 1×1 subplots, axes is a single object, not an array. |
| Overlapping labels | Call fig.tight_layout() or use layout=’constrained’. |
Practice Exercises
- Show a dataset’s 4 numeric columns as 4 histograms in a 2×2 grid.
Interview Questions
Q: subplot vs subplots?
subplot adds one axes at a position; subplots creates the figure and all axes at once.
Summary
Create grids with fig, axes = plt.subplots(rows, cols), draw on each axes, and call tight_layout().
Next: Real Stock Data Plotting
Machine Learning Tutorials, Courses and Certifications