Subplots and Layout
Python · Data Visualization
Theory
plt.subplots(nrows, ncols) creates a grid of Axes in one Figure and returns them as a NumPy array. fig, axes = plt.subplots(2, 2) gives axes with shape (2, 2): axes[0, 0] is top-left and axes[1, 1] bottom-right. With one row, plt.subplots(1, 3) returns a 1-D array, so you use axes[0], axes[1]. Looping over axes.flat visits every panel in turn.
figsize=(10, 6) sets the canvas size in inches. sharex=True or sharey=True makes panels use the same axis range, which keeps comparisons honest. fig.suptitle() adds one title for the whole figure. Labels of neighbouring panels often overlap, so call fig.tight_layout() at the end or create the figure with constrained_layout=True to space things automatically. Unused panels can be hidden with ax.axis('off').
Why we use it
Related charts are easier to compare side by side than in separate images. Subplots put a small dashboard of views (trend, distribution, breakdown) into one figure with consistent sizes and axes.
When to use it
Use subplots to compare the same chart across groups (small multiples) or to show different views of one dataset. Share axes when panels show the same measure. If panels have nothing in common, separate figures are clearer.
How it works
- Several charts to show together
- fig, axes = plt.subplots(rows, cols, figsize=...)
- Do panels show the same measure? Yes: Add sharex / sharey. No: Keep independent axes.
- Draw on each panel: axes[r, c] or loop over axes.flat
- fig.suptitle() and fig.tight_layout()
- One figure with a grid of charts
Syntax
fig, axes = plt.subplots(2, 2, figsize=(10, 6), sharey=True)
axes[0, 1].plot(x, y)
for ax in axes.flat: ...
fig.suptitle('...')
fig.tight_layout()Example
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
axes[0].plot([1, 2, 3])
axes[1].bar(['A', 'B'], [3, 5])
fig.tight_layout()Key points
- plt.subplots(r, c) returns an array of Axes
- Index a grid as axes[row, col]; a single row as axes[i]
- axes.flat loops over every panel
- sharex / sharey keep scales comparable
- fig.tight_layout() stops labels overlapping