Lesson 34 of 60 · python
Subplots, Grids, and Layouts
Duration: 20 minutes
Subplots and Layout Management
Often you need multiple plots in a single figure.
Simple 2×2 grid of subplots
fig, axs = plt.subplots(2, 2, figsize=(10,8))
axs[0,0].plot(x, y)
axs[0,0].set_title('Top‑Left')
axs[0,1].scatter(x, y)
axs[0,1].set_title('Top‑Right')
axs[1,0].hist(y, bins=20)
axs[1,0].set_title('Bottom‑Left')
axs[1,1].boxplot(y)
axs[1,1].set_title('Bottom‑Right')
plt.tight_layout()
plt.show()
Using GridSpec for custom layout
import matplotlib.gridspec as gridspec
fig = plt.figure(constrained_layout=True)
gs = gridspec.GridSpec(3, 3, figure=fig)
ax1 = fig.add_subplot(gs[0, :]) # first row, spanning all columns
ax2 = fig.add_subplot(gs[1:, 0:2]) # bottom‑left 2×2 block
ax3 = fig.add_subplot(gs[1:, 2]) # rightmost column, spanning rows 1‑2
Sharing axes
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, sharey=True)
Adding a single legend for all subplots
handles, labels = ax1.get_legend_handles_labels()
fig.legend(handles, labels, loc='upper center', ncol=3)