Course contents 22 / 22

22 / 22 · Scientific Python

Plotting with Matplotlib

Matplotlib's model of a figure as a tree of artists, the object-oriented API against pyplot, line, scatter, histogram, image and error-bar plots, labels, legends, log scales and subplots, saving PNG, SVG and PDF headless, and a checklist for a clear figure.

On this page 9

The previous note ended with tables of numbers: revenue per month, totals per category, the time of five ways to loop. A table answers a question you already asked; a figure shows the answer to questions you had not asked yet, such as a trend, an outlier or two curves that diverge. Matplotlib is the plotting library underneath most of the Python ecosystem: pandas’ .plot() and seaborn call it, and most training curves, feature histograms and grids of generated images in machine-learning code are drawn with it. This note gives its model of a figure, because every confusing piece of Matplotlib code mixes two ways of talking to that model. Then it goes through the common plot types, the details that make a figure readable, how to save one on a machine with no screen, and a checklist for a clear figure. It ends the course with a paragraph that ties the six sections together.

Conventions. Matplotlib 3.11.2 with NumPy 2.5.4 on CPython 3.14.7. Every snippet starts from import matplotlib; matplotlib.use("Agg"), then import matplotlib.pyplot as plt and import numpy as np, so that nothing opens a window; the saving section explains why.

Baseline: a sequence of pyplot calls#

The shortest Matplotlib program is a sequence of calls to the pyplot module:

plt.plot([0, 1, 2, 3], [0, 1, 4, 9])
plt.xlabel("x")
plt.ylabel("x squared")
plt.savefig("square.png")

Each call changes “the current figure”: plt.plot creates one if there is none and draws a line on it, plt.xlabel labels the x axis of whatever plot is current, and plt.savefig writes it out. This style comes from MATLAB, which Matplotlib was first written to imitate, and it is fine for one plot typed into a notebook. It fails as soon as there are two plots: in a grid of four, plt.xlabel labels only the plot that happens to be current, which is the last one created or touched. The state is global and hidden, like the global random state of np.random.seed: what a call does depends on what ran before it, in your code or in a library.

The Figure and its Axes#

Figure

A Matplotlib figure is a tree of artists

The parts of a figure and the tree of Figure, Axes and artistsA drawn figure: a canvas, inside it a plotting area with the title squares, a curve, five points, a legend and ticks on both axes. The tree: Figure, below it Axes, below the Axes six nodes: XAxis, YAxis, Line2D, PathCollection, Text, Legend.Figure · the canvasAxes · a plotting areasquares012024xydataFigurefigAxesfig.axes[0], axXAxisax.xaxisYAxisax.yaxisLine2Dax.lines[0]PathCollectionax.collections[0]Textax.titleLegendax.get_legend()a backend renders the tree: Agg → PNG; svg, pdf → vector filesThe parts of a figure and the tree of Figure, Axes and artistsA drawn figure: a canvas, inside it a plotting area with the title squares, a curve, five points, a legend and ticks on both axes. The tree: Figure, below it Axes, below the Axes six nodes: XAxis, YAxis, Line2D, PathCollection, Text, Legend.Figure · the canvasAxes · a plotting areasquares012024xydataFigurefigAxesfig.axes[0], axXAxisax.xaxisYAxisax.yaxisLine2Dax.lines[0]PathCollectionax.collections[0]Textax.titleLegendax.get_legend()a backend renders the tree:Agg → PNG; svg, pdf → vector files
Left: the drawn figure; right: the tree of objects it is made of. The Figure (amber) is the whole canvas; it holds an Axes (blue), a plotting area with its own coordinates. Inside the Axes are the data artists (green: the Line2D from ax.plot and the PathCollection of points from ax.scatter), the two rulers XAxis and YAxis with their ticks and labels, the title Text and the Legend (red). Next to each node is how to reach it from code. A backend walks the tree and renders each object to pixels or to vector shapes.

Axes (a plotting area) and Axis (one ruler with ticks) are different objects with confusingly similar names. The tree can be inspected directly:

>>> fig, ax = plt.subplots()
>>> type(fig).__name__, type(ax).__name__, fig.axes == [ax]
('Figure', 'Axes', True)
>>> lines = ax.plot([0, 1, 2], [0, 1, 4], label="data")
>>> type(lines).__name__, type(lines[0]).__name__, len(ax.lines)
('list', 'Line2D', 1)
>>> title = ax.set_title("squares")
>>> type(ax.xaxis).__name__, type(ax.title).__name__
('XAxis', 'Text')
>>> fig.get_size_inches(), fig.dpi
(array([6.4, 4.8]), 100.0)

Line by line: plt.subplots() creates a Figure with one Axes and returns both. ax.plot returns a list of the Line2D artists it added, one per line, and the Axes keeps them in ax.lines. The title is a Text artist, the x axis an XAxis. Every artist has properties that can be changed after it is drawn: lines[0].set_color("red"), ax.title.set_fontsize(14). The figure’s size is in inches, 6.4 by 4.8 by default, and its resolution in dots per inch; at 100 dpi the canvas is 640×480640 \times 480 pixels.

The object-oriented API against pyplot#

The rule. There are two ways to call Matplotlib:

  • pyplot functions (plt.plot, plt.xlabel, plt.title) act on the current figure and the current Axes, which plt.gcf() and plt.gca() return.
  • Methods (ax.plot, ax.set_xlabel, ax.set_title) act on the object you name.

Use pyplot to create figures (plt.subplots) and to close them (plt.close), and methods for everything else. The names differ in a regular way: the pyplot plt.xlabel(...), plt.title(...), plt.xlim(...) are the methods ax.set_xlabel(...), ax.set_title(...), ax.set_xlim(...); ax.set(xlabel=..., title=...) sets several at once.

>>> fig, axs = plt.subplots(2, 2)
>>> axs.shape, plt.gca() is axs[1, 1]
((2, 2), True)
>>> label = plt.xlabel("x")
>>> axs[1, 1].get_xlabel(), axs[0, 0].get_xlabel()
('x', '')

plt.subplots(2, 2) returns the Figure and a 2×22 \times 2 NumPy array of Axes, indexed like any array. The current Axes is the last one created, axs[1, 1], so plt.xlabel labels only that one. With methods there is no question: axs[0, 0].set_xlabel("x") labels the plot you named. Code that builds figures in functions, loops or libraries should take an ax argument and draw on it; that is how pandas’ df.plot(ax=ax) and seaborn’s functions fit into a figure you made. The object-oriented style is the one the Matplotlib documentation recommends for anything beyond a quick look.

Plot types#

Each plotting method adds artists to an Axes and returns them.

MethodDrawsUse it forReturns
ax.plot(x, y)lines through pointsa quantity that varies continuously: a curve, a time series, a loss per epocha list of Line2D
ax.scatter(x, y)one marker per pointthe relation between two variablesa PathCollection
ax.hist(x, bins)bars of countsthe distribution of one variablecounts, bin edges, a BarContainer
ax.imshow(A)a matrix as an imageimages, heat maps, confusion matricesan AxesImage
ax.errorbar(x, y, yerr)points with error barsestimates with their uncertaintyan ErrorbarContainer
>>> fig, ax = plt.subplots()
>>> rng = np.random.default_rng(0)
>>> counts, edges, bars = ax.hist(rng.normal(size=1000), bins=5)
>>> counts, edges.round(2)
(array([  9., 124., 496., 330.,  41.]), array([-3.9 , -2.51, -1.11,  0.28,  1.67,  3.07]))
>>> im = ax.imshow(np.arange(6).reshape(2, 3))
>>> type(im).__name__, im.get_array().shape
('AxesImage', (2, 3))

hist computes the histogram and draws it: five equal-width bins between the smallest and the largest of the 1000 samples, with the counts in each. The counts are returned, so a histogram can be checked with numbers and not only by eye. imshow draws a matrix with one coloured cell per element; row 0 is at the top by default, as in an image, not at the bottom as in a plot. For an image of real data, ax.imshow(A, cmap="viridis") with fig.colorbar(im, ax=ax) adds the scale that tells what each colour means.

Labels, legends, scales and subplots#

Labels. ax.set_xlabel and ax.set_ylabel name the quantity and its unit, ax.set_title what the plot shows. Legends. Give each plotted series a label= and call ax.legend(), which collects the labelled artists of that Axes. When there are only two or three lines, a text label at the end of each line, ax.text(x, y, "train"), saves the reader the trip to the legend.

Scales. ax.set_yscale("log") (and set_xscale) places yy at a distance proportional to log⁡y\log y. Use a log scale when values span several orders of magnitude or when ratios matter more than differences: the timing figures of the NumPy and pandas notes are on log–log axes, where a cost proportional to nn is a straight line of slope 1 and a constant ratio is a constant vertical gap. A loss that falls from 2.3 to 0.01 is also read best on a log axis; on a linear one every epoch after the first few looks flat. A log axis cannot show zero or negative values.

Subplots. plt.subplots(nrows, ncols, figsize=(w, h), sharex=True, layout="constrained") creates a grid. sharex and sharey give the plots the same limits, which is what makes them comparable at a glance; layout="constrained" moves the plots so that labels and titles do not overlap. The pixel size of the result is the figure size in inches times the dpi: figsize=(4, 3) at 100 dpi is 400×300400 \times 300 pixels.

Saving figures headless#

Backends. A backend turns the artist tree into output. Interactive backends (macosx, QtAgg, TkAgg) open a window and need a display. Non-interactive backends write files: Agg renders PNG through the Anti-Grain Geometry library, and the svg and pdf backends write vector files. On a server, in a container or in a test there is no display, so scripts use Agg: matplotlib.use("Agg") before importing pyplot, or the environment variable MPLBACKEND=Agg. On this Mac the default is macosx; Matplotlib falls back to Agg on its own when it finds no display.

The rule for saving. fig.savefig(path) chooses the format from the file extension:

  • PNG is a raster: a grid of pixels, inches×dpi\text{inches} \times \text{dpi} on each side. Its size depends on the number of pixels and how well they compress, not on how many points were plotted. It blurs when enlarged. Pass dpi=200 or more for print.
  • SVG and PDF are vector formats: they store every line, marker and glyph as a shape, so they stay sharp at any zoom and their text can be searched. Their size grows with the number of drawn elements.
Figure

File size: raster against vector

PNG, SVG and PDF file size against the number of pointsThe PNG line stays below about 20 KB. The SVG and PDF lines rise from a few kilobytes at 10 points to 10.6 MB and 1.5 MB at 100 000 points.1 KB10 KB100 KB1 MB10 MB1010²10³10⁴10⁵SVG: ~106 bytes per pointPDF: ~15 bytes per pointPNG: 400 × 300 pixelsnumber of points nbytesPNG, SVG and PDF file size against the number of pointsThe PNG line stays below about 20 KB. The SVG and PDF lines rise from a few kilobytes at 10 points to 10.6 MB and 1.5 MB at 100 000 points.1 KB10 KB100 KB1 MB10 MB1010²10³10⁴10⁵SVG: ~106 bytes per pointPDF: ~15 bytes per pointPNG: 400 × 300 pixelsnumber of points nbytes
The size of a file holding a scatter plot of n points, saved in three formats, both axes logarithmic. The figure is 4 × 3 inches at 100 dpi; measured once with Matplotlib 3.11.2 on macOS. A PNG stores 400 × 300 pixels and stays under about 20 KB at every n. SVG and PDF store every point as a shape and grow linearly, by about 106 and 15 bytes per point.

The figure measures it: a scatter plot of nn points, 4×34 \times 3 inches at 100 dpi, saved in each format. The PNG stays under about 20 KB whatever nn; the SVG grows by about 106 bytes per point and the PDF by about 15, so at 100 000 points the SVG is 10.6 MB. Use a vector format for line plots and diagrams with few elements, PNG for images and for plots with many thousands of points (or rasterized=True on the dense artist, which embeds it as pixels inside a vector file).

The mistake. pyplot keeps every figure it created in a registry until plt.close is called, so a loop that creates a figure per iteration and only saves it keeps them all in memory:

>>> plt.close("all")
>>> for k in range(21):
...     fig = plt.figure()
...
<python-input-1>:2: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`). Consider using `matplotlib.pyplot.close()`.
>>> len(plt.get_fignums())
21
>>> plt.close("all")
>>> len(plt.get_fignums())
0

Call plt.close(fig) after savefig in any loop. Alternatively, matplotlib.figure.Figure() creates a figure outside pyplot’s registry, which is freed like any Python object when the last reference goes (how CPython runs code).

A checklist for a clear figure#

A figure is an argument. These rules follow from what a reader has to do to get the argument out of it (Rougier, Droettboom and Bourne, 2014):

  1. One message. Decide what the figure should show before drawing it, and write it as the title or the first sentence of the caption. Everything else serves that message.
  2. Label the axes with the quantity and its unit. “time (ms)”, not “t”. A reader who sees only the figure must know what is plotted.
  3. Choose the scale for the question. Linear for differences, log for ratios and for data spanning decades. Start the axis of a bar chart at zero, since the bar’s length is the value.
  4. Make comparisons easy. Put the things to compare in one Axes or in subplots with shared axes, side by side along the axis being compared.
  5. Label directly when you can, with text next to each line; otherwise use a legend in a place that covers no data.
  6. Use colour with a meaning, consistently across figures, and from a colourblind-safe palette; Matplotlib’s default cycle and viridis qualify. Never let colour be the only way to tell two series apart in a figure that may be printed in grey: vary the marker or the line style too.
  7. Show uncertainty, and say what it is. An error bar may be a standard deviation, a standard error or a 95% confidence interval; these differ by large factors, and the caption must say which (confidence intervals).
  8. Size the text for the final size. Make the figure at the size it will be shown (figsize in inches), so that the font is readable without enlarging; a figure shrunk into a column shrinks its text with it.
  9. Make it reproducible. Draw it from a script with a fixed seed, and save it with savefig rather than a screenshot. The code that makes a figure is part of the result.

The course in one paragraph#

A Python program is a sequence of statements that the interpreter compiles to bytecode and runs, and its data are objects to which names refer: assignment binds a name and copies nothing (Getting Started). The built-in containers are those objects arranged for particular costs, a dynamic array for lists and a hash table for dictionaries and sets, and every for loop runs the iterator protocol over one of them (Data Structures). Classes let new objects take part in the same protocols through special methods, and closures, decorators, modules and type hints organize code so that it can be read and reused (Abstraction). Tests and profilers tell whether the code is right and where its time goes (Reliable Code). Underneath, CPython executes bytecode on a value stack, frees objects by reference counting, and runs one thread of Python at a time unless it is built without the GIL, which sets what is slow and what can run in parallel (Under the Hood). The scientific stack answers that cost: a NumPy array moves the loop over numbers out of the interpreter into compiled code over raw memory, pandas puts labelled columns of such arrays together into a table, and Matplotlib turns arrays into figures (Scientific Python). These are the tools that the next courses compute with. The Mathematics course supplies the vectors and matrices that NumPy stores, the Probability course the random variables that default_rng samples, and the Machine Learning course uses all three in a runnable script at the end of every note. For what runs below the interpreter, the Computer Architecture and Operating Systems course goes down to the processor.

What changed#

pyplot calls (the baseline)The object-oriented API
What a call acts onthe current figure and Axes, global statethe object you name
Several plotseach call affects the last one touchedaxs[i, j].method(...) on each
Inside functions and librariesdepends on what ran beforepass ax explicitly
Changing a plot after drawingfind it with plt.gca()keep the returned artists and set their properties
Memoryfigures kept in pyplot’s registry until plt.closethe same for plt.subplots; Figure() is freed like any object

Limitations#

  • Static figures. Matplotlib produces images and documents. Interactive figures in a browser, with zoom and hover, are the domain of other libraries (Plotly, Bokeh), and statistical plots with less code of seaborn, which is built on Matplotlib; neither is covered here.
  • Version details. The default figure size, dpi and colour cycle are those of Matplotlib 3.11 and can be changed in matplotlib.rcParams or a style sheet. File sizes depend on the version, the fonts installed and the data, which is why the measurements above state their setup.
  • This site draws its own figures. The figures in these notes are SVG built by the site from formulas and measured numbers, not Matplotlib output; the checklist above applies to both.

What you should remember#

  • A figure is a tree of artists: a Figure holds Axes, and each Axes holds the lines, points, bars, images, axes and text drawn in it.
  • Create figures with fig, ax = plt.subplots(...) and call methods on ax; pyplot functions act on whatever is current.
  • plot for curves, scatter for relations, hist for distributions, imshow for matrices, errorbar for estimates with uncertainty. Each returns the artists it drew.
  • Label every axis with its quantity and unit; use a log scale for data that span decades; share axes between plots that are compared.
  • Use the Agg backend on machines without a display. PNG for images and dense plots, SVG or PDF for line art. Close figures created in a loop.
  • A figure has one message, says what its error bars are, and is drawn by a script.

Code#

The script draws a 2×22 \times 2 figure that uses each plot type of the note on synthetic data with a fixed seed: two loss curves on a log scale, a scatter plot with its least-squares line, a histogram, and an image of a function on a grid, with error bars on the scatter plot. It saves the figure as PNG, SVG and PDF into a temporary directory that is deleted at the end, prints each file’s size and checks the PNG’s pixel size, and confirms that no figure is left open. Run it with python -I figure.py; it needs Matplotlib and NumPy and opens no window. File sizes differ with the Matplotlib version and the installed fonts.

"""A figure built with Matplotlib's object-oriented API and saved headless (Python 3.14, Matplotlib 3.x)."""
import pathlib
import tempfile

import matplotlib
matplotlib.use("Agg")                      # no display needed; must come before importing pyplot
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np

print("matplotlib", matplotlib.__version__, "backend", matplotlib.get_backend())
rng = np.random.default_rng(0)

fig, axs = plt.subplots(2, 2, figsize=(8, 6), layout="constrained")
print(type(axs).__name__, axs.shape)

# 1. Lines on a log scale: two loss curves that fall by a constant factor per epoch
epochs = np.arange(1, 51)
train = 2.3 * 0.9 ** epochs + 0.01
val = 2.3 * 0.93 ** epochs + 0.05
ax = axs[0, 0]
ax.plot(epochs, train, label="train")
ax.plot(epochs, val, label="validation", linestyle="--")
ax.set(xlabel="epoch", ylabel="loss", yscale="log", title="Loss per epoch")
ax.legend()

# 2. Scatter with the least-squares line and error bars on binned means
x = rng.uniform(0, 10, 200)
y = 1.5 * x + 2 + rng.normal(0, 2, 200)
slope, intercept = np.polyfit(x, y, 1)
bins = np.digitize(x, [2, 4, 6, 8])
centers = np.array([x[bins == b].mean() for b in range(5)])
means = np.array([y[bins == b].mean() for b in range(5)])
sems = np.array([y[bins == b].std(ddof=1) / np.sqrt((bins == b).sum()) for b in range(5)])
ax = axs[0, 1]
ax.scatter(x, y, s=8, alpha=0.5, label="data")
ax.plot([0, 10], [intercept, intercept + 10 * slope], color="black", label=f"fit: {slope:.2f}x + {intercept:.2f}")
ax.errorbar(centers, means, yerr=sems, fmt="o", color="red", capsize=3, label="bin mean ± s.e.")
ax.set(xlabel="x", ylabel="y", title="Relation")
ax.legend(fontsize=8)

# 3. Histogram: the counts are returned, so they can be checked
ax = axs[1, 0]
counts, edges, _ = ax.hist(rng.normal(size=1000), bins=20)
ax.set(xlabel="value", ylabel="count", title="Distribution")
print("histogram:", int(counts.sum()), "samples in", len(counts), "bins; tallest bin", int(counts.max()))

# 4. An image of a function on a grid, with a colour bar
g = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(g, g)
im = axs[1, 1].imshow(np.exp(-(X ** 2 + Y ** 2) / 2), extent=(-3, 3, -3, 3), origin="lower", cmap="viridis")
fig.colorbar(im, ax=axs[1, 1], label="density")
axs[1, 1].set(xlabel="x", ylabel="y", title="Image")

print("fit:", round(slope, 3), round(intercept, 3))
print("artists in the top-left Axes:", len(axs[0, 0].lines), "lines;", "y scale", axs[0, 0].get_yscale())

# 5. Save in three formats into a temporary directory, which is removed afterwards
with tempfile.TemporaryDirectory() as tmp:
    for fmt in ("png", "svg", "pdf"):
        path = pathlib.Path(tmp) / f"figure.{fmt}"
        fig.savefig(path, dpi=100)
        print(f"{fmt}: {path.stat().st_size:,} bytes, starts with {path.read_bytes()[:4]!r}")
    pixels = mpimg.imread(pathlib.Path(tmp) / "figure.png")
    print("png pixels (height, width, channels):", pixels.shape)

plt.close(fig)
print("open figures:", len(plt.get_fignums()))

# Output with CPython 3.14.7, Matplotlib 3.11.2 and NumPy 2.5.4 on macOS (arm64); file sizes vary:
# matplotlib 3.11.2 backend Agg
# ndarray (2, 2)
# histogram: 1000 samples in 20 bins; tallest bin 136
# fit: 1.449 2.094
# artists in the top-left Axes: 2 lines; y scale log
# png: 91,260 bytes, starts with b'\x89PNG'
# svg: 138,450 bytes, starts with b'<?xm'
# pdf: 53,718 bytes, starts with b'%PDF'
# png pixels (height, width, channels): (600, 800, 4)
# open figures: 0

The PNG has 800×600800 \times 600 pixels, figsize=(8, 6) times 100 dpi, with four channels (red, green, blue and opacity). The fitted slope and intercept, 1.449 and 2.094, recover the 1.5 and 2 used to generate the data up to the noise. The first four bytes identify each format: the PNG signature, the XML declaration that opens an SVG, and the PDF header.

References#