Skip to content
BIASED

Plotting with Matplotlib

The figure as a tree of artists, object methods against pyplot's hidden state, line, scatter, histogram, image and error-bar plots, labels, legends, log scales and subplots, saving PNG, SVG and PDF headless, rules for a clear figure, and a recap of the whole course.

From a table to a figure

The topic Data frames with pandas ended with tables of metrics: a row per epoch, a column per loss, a total per group. A table answers the question you asked of it. A figure shows what you did not think to ask: a trend, an outlier, two curves that drift apart.

Matplotlib is the plotting library under most of the Python ecosystem. pandas' df.plot() calls it, and so does seaborn. Most training curves, feature histograms and grids of generated images in machine-learning code are drawn with it. Install it like any package, with uv add matplotlib or python -m pip install matplotlib. The examples here were run on CPython 3.14.7 with Matplotlib 3.11.2 and NumPy 2.5.4.

Every example is a script that opens no window. It runs with the environment variable MPLBACKEND=Agg, and the block Saving without a screen explains why. This lesson cannot show pictures, so each figure is described in words.

The shortest Matplotlib program is a sequence of calls to the module pyplot. Here is losses.py:

import matplotlib.pyplot as plt
 
losses = [2.3, 1.1, 0.62, 0.41, 0.33, 0.30]
plt.plot(range(1, 7), losses)
plt.xlabel("epoch")
plt.ylabel("loss")
plt.savefig("losses.png")
$ MPLBACKEND=Agg python losses.py

It prints nothing and writes losses.png, 640 by 480 pixels on a white background. One blue line drops steeply from 2.3 at epoch 1 to 1.1 at epoch 2 and then flattens out towards 0.3. The bottom axis has ticks 1 to 6 and the label "epoch"; the left one is labelled "loss".

Each call changes "the current figure". plt.plot creates a figure if there is none and draws a line on it. plt.xlabel labels whichever plot is current, and plt.savefig writes the current figure to a file. The style imitates MATLAB, which Matplotlib was first written to resemble, and it is fine for one quick plot in a notebook.

With two plots it breaks. Which plot is current depends on what ran before, in your code or in a library you called. That is hidden global state, the same trouble as a global random seed, and the reason the topic NumPy arrays passed a generator from default_rng around instead.

A figure is a tree of artists

To see what those calls change, look at what a figure is made of. A Matplotlib figure is a tree of objects called artists.

  • At the root is a Figure: the whole canvas.
  • It holds one or more Axes. An Axes is one plotting area with its own coordinate system.
  • An Axes holds the artists that draw data: Line2D for a line, PathCollection for scatter points, Rectangle for bars, AxesImage for an image. It also holds two Axis objects, the rulers with ticks and tick labels, Text artists for the title and labels, and a Legend once you ask for one.

To draw, a backend walks the tree and renders each artist, into pixels or into vector shapes. Axes (a plotting area) and Axis (one ruler) are different classes with confusingly similar names.

The tree can be inspected like any objects. Here is tree.py:

import matplotlib.pyplot as plt
from matplotlib.artist import Artist
 
fig, ax = plt.subplots()
lines = ax.plot([1, 2, 3], [2.3, 1.1, 0.62], label="train")
ax.set_title("loss per epoch")
print(type(fig).__name__, type(ax).__name__, fig.axes == [ax])
print(type(lines).__name__, type(lines[0]).__name__, len(ax.lines))
print(type(ax.xaxis).__name__, type(ax.title).__name__)
print(all(isinstance(a, Artist) for a in [fig, ax, lines[0], ax.xaxis, ax.title]))
print(fig.get_size_inches(), fig.dpi)
$ MPLBACKEND=Agg python tree.py
Figure Axes True
list Line2D 1
XAxis Text
True
[6.4 4.8] 100.0

Read it line by line.

  • plt.subplots() creates a Figure with one Axes and returns both. The figure keeps its Axes in the list fig.axes.
  • ax.plot returns a list of the Line2D artists it added, one per line, and the Axes keeps them in ax.lines.
  • The x axis is an XAxis, the title a Text.
  • All five objects are instances of Artist, the base class of everything that can be drawn.

Artists are ordinary objects with attributes that can change after drawing: lines[0].set_color("red"), ax.title.set_fontsize(14). Keep what a plotting method returns if you mean to change it later.

The size of a figure is in inches, 6.4 by 4.8 by default, and its resolution in dots per inch (dpi). At 100 dpi the canvas is 640×480640 \times 480 pixels, the size of losses.png.

Methods instead of hidden state

There are two ways to talk to that tree.

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

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

Here is the trap, in grid.py:

import matplotlib.pyplot as plt
 
fig, axs = plt.subplots(2, 2)
print(axs.shape, plt.gca() is axs[1, 1])
plt.xlabel("epoch")
print([ax.get_xlabel() for ax in axs.flat])
axs[0, 0].plot([1, 2, 3], [2.3, 1.1, 0.62])
print(plt.gca() is axs[1, 1])
for ax in axs.flat:
    ax.set_xlabel("epoch")
print([ax.get_xlabel() for ax in axs.flat])
$ MPLBACKEND=Agg python grid.py
(2, 2) True
['', '', '', 'epoch']
True
['epoch', 'epoch', 'epoch', 'epoch']

plt.subplots(2, 2) returns the figure and a 2×22 \times 2 NumPy array of Axes, indexed like any array; axs.flat walks it in row order. The current Axes is the last one created, axs[1, 1], so plt.xlabel labels only that one. Drawing on axs[0, 0] with a method does not make it current. Methods need no such bookkeeping: each one labels exactly the Axes it is called on.

So a function that draws should take an ax parameter and draw on it. That is how df.plot(ax=ax) in pandas and seaborn's functions fit into a figure you made. Here is helper.py:

import matplotlib.pyplot as plt
 
def plot_losses(ax, losses, label):
    epochs = range(1, len(losses) + 1)
    ax.plot(epochs, losses, label=label)
    ax.set(xlabel="epoch", ylabel="loss")
 
fig, (left, right) = plt.subplots(1, 2)
plot_losses(left, [2.3, 1.1, 0.62], "run A")
plot_losses(right, [2.3, 1.4, 0.95], "run B")
print(len(left.lines), len(right.lines), right.get_xlabel())
$ MPLBACKEND=Agg python helper.py
1 1 epoch

The function reads like any other: it depends on its arguments and on nothing that ran before it. The Matplotlib documentation recommends this object-oriented style for anything beyond a quick look.

Five kinds of plot

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

Method Draws Use it for Returns
ax.plot(x, y) lines through points a curve, a time series, a loss per epoch a list of Line2D
ax.scatter(x, y) one marker per point the relation between two variables a PathCollection
ax.hist(x, bins) bars of counts the distribution of one variable counts, bin edges, a BarContainer
ax.imshow(A) a matrix as an image images, heat maps, confusion matrices an AxesImage
ax.errorbar(x, y, yerr) points with error bars estimates with their uncertainty an ErrorbarContainer

Here is kinds.py, three of them side by side:

import matplotlib.pyplot as plt
import numpy as np
 
rng = np.random.default_rng(0)
fig, axs = plt.subplots(1, 3, figsize=(9, 3), layout="constrained")
lines = axs[0].plot([1, 2, 3, 4], [2.3, 1.1, 0.62, 0.41])
points = axs[1].scatter(rng.uniform(0, 1, 50), rng.uniform(0, 1, 50))
counts, edges, bars = axs[2].hist(rng.normal(size=1000), bins=5)
for artist in [lines, points, bars]:
    print(type(artist).__name__)
print(counts, edges.round(2))
print(int(counts.sum()), len(edges))
$ MPLBACKEND=Agg python kinds.py
list
PathCollection
BarContainer
[ 10. 125. 497. 327.  41.] [-3.9  -2.51 -1.11  0.28  1.67  3.07]
1000 6

hist computes the histogram and draws it. Five bins of equal width span the range from the smallest sample, −3.9, to the largest, 3.07, and the counts add up to the 1000 samples. The counts come back as an array, so a histogram can be checked with numbers and not only by eye. On the figure the bars rise to a peak of 497 in the middle bin.

imshow draws a matrix as a grid of coloured cells, one per element. Here is confusion.py, a confusion matrix of a two-class classifier:

import matplotlib.pyplot as plt
import numpy as np
 
cm = np.array([[50, 3], [7, 40]])
fig, ax = plt.subplots(figsize=(3.5, 3), layout="constrained")
im = ax.imshow(cm, cmap="viridis")
fig.colorbar(im, ax=ax, label="count")
ax.set(xlabel="predicted class", ylabel="true class", xticks=[0, 1], yticks=[0, 1])
print(type(im).__name__, im.get_array().shape, im.origin)
fig.savefig("confusion.png")
$ MPLBACKEND=Agg python confusion.py
AxesImage (2, 2) upper

origin is upper: row 0 of the matrix is drawn at the top, as in a picture, not at the bottom as on a plot. The 50 correct answers for class 0 make the top-left cell bright yellow, and the other cells run from dark purple to green. The palette cmap="viridis" maps numbers to colours. fig.colorbar adds a bar on the right, labelled "count", that tells the reader what each colour means.

Labels, scales and grids of plots

A plot becomes readable through four details: labels, legends, scales and the layout of several plots.

  • Labels. ax.set_xlabel and ax.set_ylabel name the quantity and its unit; ax.set_title says what the plot shows.
  • Legends. Give each series a label= and call ax.legend(), which collects the labelled artists of that Axes. With two or three lines, text at the end of each line, ax.text(x, y, "train"), saves the reader a trip to the legend.
  • Scales. ax.set_yscale("log") places each value at a height proportional to its logarithm. Equal ratios become equal distances. A log axis cannot show zero or negative values.
  • Grids. plt.subplots(nrows, ncols, sharex=True, layout="constrained") creates a grid. sharex and sharey give the plots the same limits, so they can be compared at a glance. layout="constrained" moves the plots so that labels and titles do not overlap.

Here is scales.py: the same two loss curves on a linear and on a log axis.

import matplotlib.pyplot as plt
import numpy as np
 
epochs = np.arange(1, 51)
train = 2.3 * 0.9 ** epochs + 0.01
val = 2.3 * 0.93 ** epochs + 0.05
fig, axs = plt.subplots(1, 2, figsize=(8, 3), sharex=True, layout="constrained")
for ax, scale in zip(axs, ["linear", "log"]):
    ax.plot(epochs, train, label="train")
    ax.plot(epochs, val, label="validation", linestyle="--")
    ax.set(xlabel="epoch", ylabel="cross-entropy loss", yscale=scale, title=scale)
axs[1].legend()
print(train[[0, 9, 49]].round(3), val[[0, 9, 49]].round(3))
print(axs[1].get_yscale(), axs[1].get_legend_handles_labels()[1])
fig.savefig("scales.png")
$ MPLBACKEND=Agg python scales.py
[2.08  0.812 0.022] [2.189 1.163 0.111]
log ['train', 'validation']

On the left, linear panel both curves fall steeply over the first 20 epochs and then crawl along the bottom. By epoch 50 they are 0.09 apart on an axis that spans 2.2, and the gap looks negligible. On the right, log panel the solid train line is nearly straight and falls from 2 to about 0.02. The dashed validation line falls more slowly, and the two curves fan apart: by epoch 50 the validation loss is five times the training loss. That gap is the overfitting the linear axis hid. The x axis has the same limits in both panels because of sharex=True.

Use a log scale when values span several orders of magnitude or when ratios matter more than differences. A loss that falls from 2.3 to 0.02 is such a value; so is a running time measured for nn from 10 to a million.

The pixel size of a saved figure is its size in inches times the dpi: figsize=(8, 3) at 100 dpi gives an image 800 pixels wide and 300 high.

Saving without a screen

A backend turns the tree of artists into output. Interactive backends (macosx, QtAgg, TkAgg) open a window and need a display. Non-interactive ones write files: Agg renders PNG through the Anti-Grain Geometry library, and the svg and pdf backends write vector files.

A server, a container or a test has no display, so scripts there use Agg. Set it with MPLBACKEND=Agg or with matplotlib.use("Agg") before the first import matplotlib.pyplot. On the Mac used for this topic the default backend is macosx; where there is no display, Matplotlib falls back to Agg by itself.

fig.savefig(path) picks the format from the extension.

  • PNG is a raster: a grid of pixels, inches times dpi on each side. It blurs when enlarged. Pass dpi=200 or more for print.
  • SVG and PDF are vector formats. They store every line, marker and letter as a shape, so they stay sharp at any zoom and their text can be searched.

Here is formats.py, a scatter plot of 100 and of 10 000 points saved three ways:

import os
import matplotlib.pyplot as plt
import numpy as np
 
rng = np.random.default_rng(0)
for n in [100, 10_000]:
    fig, ax = plt.subplots(figsize=(4, 3))
    ax.scatter(rng.normal(size=n), rng.normal(size=n), s=4)
    for ext in ["png", "svg", "pdf"]:
        fig.savefig(f"scatter.{ext}", dpi=100)
        print(n, ext, os.path.getsize(f"scatter.{ext}"), "bytes")
    plt.close(fig)
print(plt.imread("scatter.png").shape)
$ MPLBACKEND=Agg python formats.py
100 png 6325 bytes
100 svg 18808 bytes
100 pdf 6821 bytes
10000 png 20600 bytes
10000 svg 1072000 bytes
10000 pdf 157585 bytes
(300, 400, 4)

The exact sizes depend on the Matplotlib version and the installed fonts; the pattern does not. The PNG stays small whatever the number of points, because its size is set by its pixels. The SVG grows by about 106 bytes per point and the PDF by about 15. The PNG read back is 300 rows by 400 columns with four channels: red, green, blue and opacity. Use a vector format for line plots and diagrams, and PNG for images and for plots with many thousands of points.

pyplot also keeps every figure it created in a registry until plt.close is called. Here is runs.py, a loop that saves one figure per run and never closes them:

import matplotlib.pyplot as plt
 
for run in range(21):
    fig, ax = plt.subplots()
    ax.plot([1, 2, 3], [2.3, 1.1, 0.62])
    fig.savefig(f"run{run}.png")
print(len(plt.get_fignums()))
plt.close("all")
print(len(plt.get_fignums()))
$ MPLBACKEND=Agg python runs.py
.../runs.py:4: 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()`.
  fig, ax = plt.subplots()
21
0

Rebinding fig on the next iteration frees nothing, because the registry still refers to every figure. Call plt.close(fig) after savefig in any loop. Or create the figure outside pyplot with matplotlib.figure.Figure() and fig.subplots(): the registry never sees it, so plt.get_fignums() stays empty and the figure is freed like any object.

Rules 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; they are adapted from Rougier, Droettboom and Bourne, Ten simple rules for better figures (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.
  2. Label every axis with the quantity and its unit: "time (ms)", not "t".
  3. Choose the scale for the question. Linear for differences, log for ratios and for data that span decades. A bar chart starts at zero, because the length of a bar is its value.
  4. Make comparisons easy. Put what is compared on one Axes, or on neighbouring plots with shared axes.
  5. Label directly when you can, with text next to each line. Otherwise place the legend where it covers no data.
  6. Use colour with a meaning, the same way in every figure, from a palette that colour-blind readers can tell apart; Matplotlib's default colours and viridis qualify. Never let colour be the only difference between two series: vary the line style or the marker too.
  7. Show uncertainty and say what it is. An error bar can be a standard deviation, a standard error or a 95% confidence interval. These differ by large factors, so the figure must say which.
  8. Make it at its final size, and make it reproducible. Set figsize to the size at which it will be shown, so the text is readable without enlarging. Draw it from a script with a fixed seed and save it with savefig, never as a screenshot.

Here is accuracy.py, which follows them for the validation accuracy of five training runs with different seeds:

import matplotlib.pyplot as plt
import numpy as np
 
rng = np.random.default_rng(0)
epochs = np.arange(1, 11)
acc = 0.95 - 0.4 * 0.7 ** epochs + rng.normal(0, 0.01, size=(5, 10))  # 5 seeds
mean = acc.mean(axis=0)
sem = acc.std(axis=0, ddof=1) / np.sqrt(5)
fig, ax = plt.subplots(figsize=(4, 3), layout="constrained")
ax.errorbar(epochs, mean, yerr=sem, fmt="o-", capsize=3, label="mean ± s.e., 5 seeds")
ax.set(xlabel="epoch", ylabel="validation accuracy", title="Most of the gain is in 5 epochs")
ax.legend(loc="lower right")
fig.savefig("accuracy.pdf")
print(mean[[0, 4, 9]].round(3), sem.max().round(4))
$ MPLBACKEND=Agg python accuracy.py
[0.664 0.882 0.944] 0.0063

The PDF shows one line of round markers that climbs from 0.66 at epoch 1 to 0.88 at epoch 5 and then creeps up to 0.94. The title states the message, and the numbers back it: 0.22 of the total gain of 0.28 comes in the first four steps. The error bars are so short that they barely stick out of the markers. The legend in the free lower-right corner says what they are, a standard error over 5 seeds, so a reader knows the runs agree closely.

What happens when Python runs your code

This topic closes the course. It began with one question: what actually happens when Python runs your code, and how do you use that to write programs that are correct, clear and fast enough for machine learning? Here is the answer in six parts.

  1. Getting started. The interpreter compiles a file to bytecode and runs it. Its data are objects, and names refer to them; assignment binds a name and copies nothing.
  2. Data structures. Lists are dynamic arrays and dicts and sets are hash tables, so each operation has a known cost. Every for loop runs the iterator protocol, and an exception unwinds the calls until something handles it.
  3. Abstraction. Classes let new objects join the same protocols through special methods. Closures, decorators, modules and type hints organize code so that others can read and reuse it.
  4. Reliable code. Tests say whether the code is right; debuggers and profilers say where it goes wrong and where its time goes.
  5. Under the hood. CPython runs bytecode on a value stack, frees an object when its reference count drops to zero, and runs one thread of Python at a time unless it is the free-threaded build. That decides what is slow and what can run in parallel.
  6. Scientific Python. NumPy moves the loop over numbers out of the interpreter into compiled code over raw memory. pandas puts labelled columns of such arrays into a table, and Matplotlib turns arrays into figures.

The last topic used all six. A figure is a tree of objects, and fig and ax are names that refer to them. pyplot's current figure is hidden state, and the cure is the cure from the topic Functions: pass what a function works on as an argument. The registry leaks figures for a reason from the topic How CPython runs code: an object lives while something refers to it. And Agg lets a figure be drawn in a test or on a server, where nobody looks at a screen.

Two courses build on this one. Machine Learning goes from the learning problem and validation through linear models, trees and gradient boosting to neural networks. It computes with NumPy arrays and pandas tables and reads learning curves like the ones in this topic. Deep Learning trains networks in PyTorch. A network there is a class whose instances are called like functions, the data model of part 3, and its tensors are arrays with a shape and a dtype, as in NumPy. Both courses ask you to read code and its output the way this one did: run it, look at what it printed, and explain why.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.