Figures and Axes

fig, ax = plt.subplots() — the object-oriented API.

A Figure is the whole window. An Axes is one plotting area inside it. plt.subplots() creates both. Then you call ax.plot instead of plt.plot.

Goal

Build a figure with subplots, set titles on ax, and prefer this style for the rest of the course.

The pattern

x = np.linspace(0, 2 * np.pi, 80)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x))
ax.set_title("sin")
ax.set_xlabel("x")
ax.set_ylabel("sin(x)")
plt.show()

set_title / set_xlabel are the Axes versions of plt.title / plt.xlabel.

Size

fig, ax = plt.subplots(figsize=(6, 3.2))
ax.plot([0, 1, 2], [0, 1, 4], marker="o")
ax.set_title("figsize=(6, 3.2)")
plt.show()

figsize is width × height in inches. On this editor it still scales to the Plot panel.

Two named Axes

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

Unpacking (ax_left, ax_right) beats axes[0] when there are only two panels.

You should see

fig is the container; ax is where the data go. Later chapters use this pair almost everywhere.