Figures & Axes (OO API)
So far most examples used pyplot functions like plt.plot() and plt.title(), which act on an invisible "current" plot. Behind them is Matplotlib's object-oriented (OO) API, where you hold explicit references to the objects you draw on. Once a figure has more than one panel, the OO style is clearer, and it is the style used in Matplotlib's own documentation and in most real code.
The anatomy of a figure
| Object | What it is |
|---|---|
Figure |
The whole canvas: the image or window. Holds one or more Axes, plus figure-level text like suptitle |
Axes |
One plotting area with its own coordinate system, data, title and labels. Not the same as "axis" |
Axis |
One number line of an Axes (ax.xaxis, ax.yaxis) with ticks and tick labels |
Artist |
Everything visible: lines, text, patches (rectangles, wedges), images. Even the Figure and Axes are artists |
fig, ax = plt.subplots()
The usual starting point creates a figure with one Axes and returns both:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 100)
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(x, np.sqrt(x), label="sqrt(x)")
ax.plot(x, np.log1p(x), label="log(1 + x)")
ax.set_title("Two slowly growing functions")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.legend()
plt.show()
print(type(fig).__name__, "with", len(fig.axes), "Axes")
print("Figure size in inches:", fig.get_size_inches().tolist())
print("Pixel size at dpi", fig.dpi, "=", (fig.get_size_inches() * fig.dpi).tolist())Figure with 1 Axes
Figure size in inches: [6.0, 4.0]
Pixel size at dpi 100.0 = [600.0, 400.0]
pyplot names vs. Axes methods
Most pyplot functions have an Axes method with a set_ prefix:
| pyplot | Axes method |
|---|---|
plt.plot(...) |
ax.plot(...) |
plt.title(t) |
ax.set_title(t) |
plt.xlabel(t) / plt.ylabel(t) |
ax.set_xlabel(t) / ax.set_ylabel(t) |
plt.xlim(a, b) / plt.ylim(a, b) |
ax.set_xlim(a, b) / ax.set_ylim(a, b) |
plt.xticks(...) |
ax.set_xticks(...), ax.set_xticklabels(...) |
plt.legend() |
ax.legend() |
plt.grid() |
ax.grid() |
ax.set() sets several properties in one call, which keeps setup code compact:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.bar(["A", "B", "C"], [5, 9, 3], color="C4")
ax.set(title="Scores", xlabel="Player", ylabel="Points", ylim=(0, 10))
plt.show()
print(ax.get_title(), ax.get_xlabel(), ax.get_ylabel(), [float(v) for v in ax.get_ylim()])Scores Player Points [0.0, 10.0]
Writing reusable plotting functions
The biggest advantage of the OO API: a function can accept an ax parameter and draw on whatever Axes you give it. The same function then works for a single chart or one panel in a grid:
import numpy as np
import matplotlib.pyplot as plt
def plot_series(ax, values, title, color="C0"):
"""Draw a series with its mean as a dashed line."""
ax.plot(values, color=color, marker="o", ms=4)
ax.axhline(np.mean(values), color=color, linestyle="--", alpha=0.6)
ax.set_title(title)
return np.mean(values)
shop_a = [12, 15, 11, 18, 21, 19, 24]
shop_b = [20, 18, 22, 17, 16, 19, 15]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 3.5), sharey=True)
mean_a = plot_series(ax1, shop_a, "Shop A")
mean_b = plot_series(ax2, shop_b, "Shop B", color="C1")
fig.supxlabel("Day")
fig.tight_layout()
plt.show()
print(f"Means: A={mean_a:.1f}, B={mean_b:.1f}")Means: A=17.1, B=18.1
Unpacking (ax1, ax2) directly from plt.subplots(1, 2) is a common idiom when the grid is small.
Adding Axes by hand
fig.add_subplot() adds a grid cell, and fig.add_axes([left, bottom, width, height]) places an Axes anywhere, using fractions of the figure (0 to 1). That is how you make an inset:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-5, 5, 400)
y = np.sinc(x)
fig = plt.figure(figsize=(6, 4))
ax = fig.add_subplot() # one Axes filling the figure
ax.plot(x, y)
ax.set_title("sinc(x) with a zoomed inset")
inset = fig.add_axes([0.62, 0.55, 0.25, 0.25])
inset.plot(x, y, color="C3")
inset.set_xlim(1, 3)
inset.set_ylim(-0.25, 0.15)
inset.set_title("zoom", fontsize=8)
plt.show()
print("Axes in figure:", len(fig.axes))
print("Inset position:", [round(float(v), 2) for v in inset.get_position().bounds])Axes in figure: 2
Inset position: [0.62, 0.55, 0.25, 0.25]
Mixing the two styles
pyplot and the OO API are interchangeable: plt.gcf() and plt.gca() hand you the current objects, and plt.sca(ax) makes an Axes current. A good rule of thumb:
- Quick one-off chart → pyplot is fine.
- Several panels, functions, or anything you'll maintain → OO API.
- Use
plt.subplots()andplt.show()from pyplot in both cases.
Note: "Axes" (the plotting area) and "axis" (one number line) sound alike but are different objects. A 2-D Axes has two Axis objects:
ax.xaxisandax.yaxis.
Test yourself
What does fig, ax = plt.subplots() return?
- Two figures
- A Figure and a single Axes
- An Axes and an Axis
- A list of lines
Which Axes method corresponds to plt.xlabel()?
- ax.xlabel()
- ax.set_xlabel()
- ax.label_x()
- ax.xaxis.label()
In fig.add_axes([0.1, 0.1, 0.5, 0.3]), what units are the numbers in?
- Inches
- Pixels
- Fractions of the figure width/height
- Data coordinates