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
fig, axes = plt.subplots(2, 2, figsize=(10, 8))axes[0, 0].plot(x, y1) # index into the 2-D arrayaxes[0, 1].scatter(x, y2)axes[1, 0].bar(cats, vals)axes[1, 1].hist(data)fig.suptitle("Dashboard") # a title for the whole figurefig.tight_layout() # prevent overlapping labelsplt.show()
Iterating over Axes
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
- 01plt.subplots(rows, cols) creates a grid of Axes in one Figure.
- 02Index a 2-D grid as axes[row, col]; loop over a 1-D row/column.
- 03fig.suptitle sets a title for the whole figure.
- 04fig.tight_layout() prevents overlapping labels between subplots.
