Figures, Axes and pyplot

Matplotlib · Essentials · 10 min

Every customization you will ever do is a method on a Figure or an Axes, so this mental model makes the rest of the library predictable.

A Matplotlib chart is a small tree of objects. At the top is the Figure: the whole canvas, with a size in inches and a resolution in dots per inch. Inside it live one or more Axes: a plotting area with an x axis, a y axis, a title and the data you draw. Note the spelling: an Axes is one plot; an Axis is one of its two number lines.

The usual entry point is matplotlib.pyplot, imported as plt. The idiomatic start is:

fig, ax = plt.subplots()

which creates a Figure with a single Axes and returns both. You then call methods on ax to draw (ax.plot, ax.bar) and to decorate (ax.set_title, ax.set_xlabel). Finally you either show the figure in a window or notebook with plt.show(), or write it to a file with fig.savefig("chart.png").

  • figsize=(width, height) is in inches; dpi turns inches into pixels when saving a raster image.
  • Each Axes has its own data limits, so two side-by-side plots can use different scales.
  • pyplot keeps a notion of the "current" figure and axes, which is what the short plt.plot(...) style draws on.

When nothing appears, it is usually because the script never called plt.show(), or it is running without a display (a server), where you should save to a file instead.

Example

import matplotlib
matplotlib.use("Agg")              # no window needed, e.g. on a server
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6, 4))
ax.plot([1, 2, 3, 4], [1, 4, 9, 16])
ax.set_title("Squares")

print(type(fig).__name__)          # Figure
print(type(ax).__name__)           # Axes
print(fig.get_size_inches())       # [6. 4.]
print(len(fig.axes))               # 1
fig.savefig("squares.png", dpi=100)  # 600 x 400 pixels

Remember

  • A Figure is the canvas; an Axes is one plot inside it
  • fig, ax = plt.subplots() is the standard way to start
  • Draw and decorate by calling methods on ax; save with fig.savefig

Watch out for

  • Confusing Axes (a plot) with Axis (the x or y number line).

Check yourself

  1. What does `fig, ax = plt.subplots()` return?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: matplotlib.org/stable/users/explain/quick_start.html