Subplots

Several Axes on one Figure, sharex, and tight_layout.

Several Axes on one Figure let you compare charts without stacking Runs. plt.subplots(rows, cols) returns an array of Axes.

Goal

Build a 1×2 and a 2×2 grid, share an x-axis, and call tight_layout.

Side by side

x = np.linspace(0, 2 * np.pi, 80)
fig, axes = plt.subplots(1, 2, figsize=(8, 3.2))
axes[0].plot(x, np.sin(x))
axes[0].set_title("sin")
axes[1].plot(x, np.cos(x), color="C1")
axes[1].set_title("cos")
fig.tight_layout()
plt.show()

2×2

x = np.linspace(0, 2 * np.pi, 80)
fig, axes = plt.subplots(2, 2, figsize=(7, 6))
axes[0, 0].plot(x, np.sin(x))
axes[0, 0].set_title("sin")
axes[0, 1].plot(x, np.cos(x))
axes[0, 1].set_title("cos")
axes[1, 0].plot(x, np.sin(x) ** 2)
axes[1, 0].set_title("sin²")
axes[1, 1].plot(x, np.abs(np.sin(x)))
axes[1, 1].set_title("|sin|")
fig.tight_layout()
plt.show()

axes is 2-D. axes[1, 0] is bottom left.

Shared x

x = np.linspace(0, 4, 80)
fig, axes = plt.subplots(2, 1, sharex=True, figsize=(6, 5))
axes[0].plot(x, np.exp(-x))
axes[0].set_ylabel("exp(-x)")
axes[1].plot(x, np.exp(-x) * np.sin(6 * x), color="C1")
axes[1].set_ylabel("damped")
axes[1].set_xlabel("x")
fig.tight_layout()
plt.show()
Pitfall

plt.subplot(2, 2, 3) (singular) is the old pyplot state API. Prefer fig, axes = plt.subplots(...) so each panel has a name.