Skip to main content
Albero Academy

Subplots

Put multiple plots in one figure with a grid of Axes.

Figures & Layout9 min

Often you want several plots side by side — small multiples, or different views of the same data. plt.subplots(rows, cols) creates a grid of Axes in one Figure, returning them as an array.

A grid of Axes

rows × cols of plots
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
axes[0, 0].plot(x, y1) # index into the 2-D array
axes[0, 1].scatter(x, y2)
axes[1, 0].bar(cats, vals)
axes[1, 1].hist(data)
fig.suptitle("Dashboard") # a title for the whole figure
fig.tight_layout() # prevent overlapping labels
plt.show()

Iterating over Axes

loop over a flat array
fig, axes = plt.subplots(1, 3, figsize=(12, 4))
for ax, col in zip(axes, ["a", "b", "c"]):
ax.plot(df[col])
ax.set_title(col)

Key takeaways

  1. 01plt.subplots(rows, cols) creates a grid of Axes in one Figure.
  2. 02Index a 2-D grid as axes[row, col]; loop over a 1-D row/column.
  3. 03fig.suptitle sets a title for the whole figure.
  4. 04fig.tight_layout() prevents overlapping labels between subplots.

Finished this chapter?

Mark it complete to track your progress through Matplotlib.