Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 2: Programming Toolkit

Plotting with Matplotlib

P2.440 min●○○ BeginnerReviewed Dec 1, 2026

Why this matters for machine learning

You cannot judge a model, or a data set, from a column of numbers: you plot a training run, a feature, a prediction or an image, and the picture shows the problem (overfitting, an outlier, an imbalanced class) that a single score hides.

Before this: Python essentials for ML, NumPy: arrays and vectorization

After this lesson you can

  • Create a Figure and an Axes with fig, ax = plt.subplots(), say what each one is, and say why the Figure-and-Axes style is safer than the pyplot shortcuts
  • Draw a line plot (with a log y-axis for a loss curve), a scatter plot coloured by class, a histogram with a chosen bin count, a bar chart and an image or matrix with imshow, each with labels, a legend and a colour bar where needed
  • Build a grid of subplots with shared axes, set limits and scales, and save a figure with savefig at the dpi and format you need
  • Choose bins, colour maps and axis ranges that tell the truth about the data, and avoid the common mistakes (missing labels, shape traps, truncated bars, rainbow colour maps)

You trained a small network for 40 epochs and your code printed 40 numbers for the training loss and 40 for the validation loss. Somewhere in those 80 numbers is the answer to the question “should I stop training?”, but nobody can read it from the list. Draw them as two lines, and in one second you see the training loss still falling while the validation loss turned up around epoch 22. A plot is the fastest way to find out what your numbers are doing.

Matplotlib is the standard Python library for drawing such plots. Almost every ML tutorial, paper notebook and library plots with it, or with a tool built on it (pandas plotting in P2.5, and seaborn, a library that draws statistical plots on top of Matplotlib). This lesson teaches the small part of it that you use constantly, and the habits that keep the pictures honest.

On this page you can run real Matplotlib in your browser. Each runnable plot below already shows its picture, so you can read the whole lesson without running anything. If you press Run, the first run downloads about 19 MB (the box tells you before it starts) and then every plot on the page draws quickly.

Two objects: Figure and Axes

Start with the picture in your head. A Figure is the whole sheet of paper (or the whole image file). An Axes is one plot drawn on that sheet: the rectangle with the data, the ticks, the labels and the title. One Figure can hold one Axes or many. The x-axis and the y-axis, the two lines with their numbers, are each an Axis. The word is easy to confuse with Axes, so read the plural carefully. The things you draw are called artists: lines, dots, bars, text.

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 50)

fig, ax = plt.subplots()      # a new Figure with one Axes
ax.plot(x, np.sin(x))         # draw on that Axes
ax.set_title("sin")           # decorate that Axes

plt.subplots() returns two things: the Figure fig and the Axes ax. Everything you draw or label is a method call on ax (ax.plot, ax.set_xlabel, ax.set_title), and things about the whole picture are methods on fig (fig.savefig, fig.colorbar, fig.suptitle).

There is a second style, which you will see in many tutorials. The pyplot functions (plt.plot, plt.title) draw on a hidden “current Axes”, which they create for you if needed:

plt.plot(x, np.sin(x))        # draws on the current Axes (made automatically)
plt.title("sin")              # titles the current Axes

Both give the same picture. The first style is called the object-oriented (or explicit) style, the second the pyplot (or implicit) style. This lesson uses the first, and you should too, for three reasons.

  • You always know where a drawing goes. With several plots, plt.title("A") goes to whichever Axes happens to be current, which is the last one you touched. Calling ax2.set_title("A") has only one meaning.
  • It scales. Grids of plots, a function that draws on an Axes you pass in, and two figures open at once all work without surprises. The Matplotlib documentation describes both styles and lists the trade-offs; the explicit one is what it recommends for anything beyond a quick look.
  • The names are the same everywhere. plt.xlabel becomes ax.set_xlabel, plt.xlim becomes ax.set_xlim, plt.legend stays ax.legend: add set_ when the pyplot function sets a property.

Pyplot is not wrong. It is the shortest way to draw one quick plot in a notebook. A good rule: pyplot to create the figure, methods on fig and ax for everything else (that is exactly what plt.subplots does). Mixing the two styles is the source of many “my title went to the wrong plot” mistakes.

Line plots: the loss curve

A line plot connects points (x[0], y[0]), (x[1], y[1]), ... in order. It suits a quantity that changes along an ordered x, such as a loss per epoch, a learning rate per step or a function of time. In ML you draw it more than any other plot.

ax.plot(x, y)                                  # x and y: arrays of the same length
ax.plot(y)                                     # only y: x becomes 0, 1, 2, ...
ax.plot(x, y, color="#0072B2", linestyle="--", linewidth=2, marker="o", label="train")

The useful options are color, linestyle ("-", "--", ":"), linewidth, marker ("o" circle, "^" triangle, "s" square) and label. Each call to ax.plot adds one more line to the same Axes, and ax.legend() shows the labels you gave. The usual way to get a training curve is to record the loss in a list while the loop runs, and to plot the list afterwards:

losses = []
for step in range(30):
    loss = ...            # your training step goes here
    losses.append(loss)   # remember it

fig, ax = plt.subplots()
ax.plot(losses)           # x is the step number 0, 1, 2, ...
ax.set_xlabel("step")
ax.set_ylabel("loss")

Now the first live plot. It draws a made-up 40-epoch run with the training loss falling steadily while the validation loss turns up (overfitting, P3.A3). It also uses a log scale on the y-axis.

Run it: loss curves on a log axis

Optional: runs real Matplotlib in your browser. The first run downloads about 19 MB (Python 6 MB, then Matplotlib with NumPy 13 MB), once; your browser keeps it (less if you already ran another Python cell on this site). The picture below is what the code draws.

Line plot of loss against epoch, from 1 to 40, with a logarithmic y-axis. The solid blue training loss falls from about 1.8 to about 0.04. The dashed reddish-purple validation loss falls to about 0.58 near epoch 22, then rises slowly to about 0.75. A dotted vertical line marks epoch 22.

A made-up training run: the training loss (solid blue line) keeps falling, the validation loss (dashed reddish-purple line) flattens and then rises. The dotted grey line marks the epoch with the lowest validation loss, epoch 22, where the code prints a validation loss of 0.576. The y-axis is logarithmic, so each tick is ten times the one below it.

Three things in that code deserve a word.

Log scale, ax.set_yscale("log"). A loss often starts near 2 and ends near 0.02: a factor of 100. On a linear axis, everything below 0.2 is squeezed into the bottom tenth of the picture and you cannot see whether the training loss is still improving. On a log axis, equal ratios get equal vertical distance, so falling from 2 to 0.2 takes the same height as falling from 0.2 to 0.02, and a curve that decays like e−kte^{-kt} becomes a straight line. A log axis cannot show zero or negative values (the logarithm is undefined there), so it suits a loss, which is positive. Remove the set_yscale line in the runner and compare. (Use set_xscale("log") for an x such as a learning rate that you vary over several powers of ten.)

Reading the picture. If both curves fall together, the model is still learning. If the training loss falls and the validation loss turns up, the model is memorizing the training data: that is overfitting, and the epoch where the validation loss is lowest is where you would have stopped (P4.22 teaches a whole gallery of such shapes). Plotting the validation loss as well as the training loss is what makes this visible. The two losses are measured on different data: the training set and a held-out validation set (P3.A4).

figsize and tight_layout. figsize=(4.5, 3) is the width and height of the Figure in inches. The default is (6.4, 4.8) and the default resolution is 100 dots per inch, so the default picture is 640 by 480 pixels. fig.tight_layout() adjusts the spacing so that labels do not overlap or get cut off.

Scatter plots: two features, coloured by class

A scatter plot draws one dot per example at its two feature values. It shows clusters, trends and outliers, and it is the basic picture of a classification problem (P1.D7 used it to show what a correlation hides).

ax.scatter(x, y)                      # one dot per (x[i], y[i])
ax.scatter(x, y, s=20, alpha=0.6, color="#0072B2", marker="o", label="class 0")
  • s is the marker area in points squared (a point is 1/72 inch), so doubling the width of a dot means multiplying s by 4. The default is 36.
  • alpha is opacity from 0 (invisible) to 1. When many dots land on top of each other (overplotting), the blob looks like one solid shape and hides how dense it is. Small dots (s=5 to s=20) and alpha around 0.2 to 0.6 let you see density, because overlapping dots then look darker.
  • To colour by class, draw one scatter call per class, using a Boolean mask to pick the rows, and give each a label. If X has shape (n, 2) and y holds the class labels with shape (n,):
for k, name in enumerate(["class 0", "class 1"]):
    ax.scatter(X[y == k, 0], X[y == k, 1], label=name)

The other way is ax.scatter(X[:, 0], X[:, 1], c=y), which colours each dot by its label through a colour map; then handles, names = sc.legend_elements() (where sc is the object scatter returned) gives you legend entries. The loop is simpler to read and lets you change the marker per class.

Run it: scatter plot coloured by class

Optional: runs real Matplotlib in your browser. The first run downloads about 19 MB (Python 6 MB, then Matplotlib with NumPy 13 MB), once; your browser keeps it (less if you already ran another Python cell on this site). The picture below is what the code draws.

Scatter plot of feature 2 against feature 1. Blue circles (class 0) cluster around feature 1 of 2 and feature 2 of 2. Reddish-purple triangles (class 1) cluster up and to the right, around 3.2 and 3. The two clouds overlap in the middle.

Two made-up features for 150 examples of class 0 (blue circles) and 150 of class 1 (reddish-purple triangles). The classes overlap in the middle. The dots are small and half transparent, and the classes differ in marker shape as well as colour, so the picture still works for a reader who cannot tell blue from reddish purple.

A scatter plot is also the quickest look at a classification problem: if one straight line could separate the two colours, a linear classifier such as logistic regression (P3.A7) would do well; if the colours mix as they do here, even the best line makes some mistakes, and you may want more features or a model that can bend, such as a neural network (Part 4).

Histograms: how bins change the story

A histogram shows how the values of one variable are spread out. Matplotlib cuts the range into bins, counts how many values fall in each, and draws one bar per bin.

ax.hist(x, bins=10)                         # 10 equal-width bins between min(x) and max(x) (the default is also 10)
ax.hist(x, bins=16, range=(0, 80))          # fix the range, so several histograms share the same bins
ax.hist(x, bins=[0, 20, 40, 80])            # or give the bin edges yourself (unequal widths allowed)
ax.hist(x, bins=8, density=True)            # heights become a probability density

ax.hist also returns the counts and the bin edges, and np.histogram(x, bins=8, range=(0, 80)) computes the same numbers without drawing. A value exactly on an edge goes into the bin on its right, except that the very last bin also includes its right edge (so a value of 80 counts in the last bin of range=(0, 80)).

The number of bins changes the story. Here are the same 60 made-up values as in the statistics lesson (P1.D12), drawn with 4, 16 and 80 bins. With 4 bins (each 20 wide) the bars read 8, 20, 29 and 3 and look like one hill. With 16 bins (each 5 wide) the picture shows two clear groups, one between about 10 and 30 and one between about 40 and 70, with an empty stretch from 30 to 40. With 80 bins (each 1 wide) the values break into thin bars: 31 of the 80 bins hold anything (1 to 5 values each), and the shape is lost in noise. Nothing in the data changed.

Run it: the same data, three bin counts

Optional: runs real Matplotlib in your browser. The first run downloads about 19 MB (Python 6 MB, then Matplotlib with NumPy 13 MB), once; your browser keeps it (less if you already ran another Python cell on this site). The picture below is what the code draws.

Three stacked histograms of the same 60 values, sharing axes from 0 to 80. With 4 bins there are four wide bars of heights 8, 20, 29 and 3. With 16 bins there are two groups of bars, one between about 10 and 30 and one between about 40 and 70, separated by empty bins from 30 to 40. With 80 bins there are thin bars of height 1 to 5.

One data set (the 60 made-up values of P1.D12, between 14.4 and 65.5), three bin counts: 4, 16 and 80 bins over the range 0 to 80. All three panels share their x and y axes, so the heights can be compared. Edit the list bins_to_try in the code to try other numbers.

There is no single right bin count. Try several, be suspicious of a feature that appears at only one of them, and when you compare two histograms use the same range and the same number of bins. Matplotlib also accepts rules such as bins="auto", which picks a count from the data (it gives 7 bins here), but a rule is a starting point, not an answer.

density=True. By default the bar height is a count. With density=True the height is the count divided by (total count times bin width), so that the area of all the bars adds up to 1. It is not that the heights add to 1. For the 8 bins of width 10 above, the bin from 20 to 30 holds 20 of the 60 values, so its height is 20/(60×10)=0.033320/(60\times10)=0.0333, and the eight areas height×10\text{height}\times10 add up to exactly 1. Use density=True when you overlay two groups of different sizes (say 900 cats and 100 dogs): counts make the small group vanish, densities compare their shapes. Remember that a density can exceed 1 for a narrow bin; it is not a probability.

Bar chart or histogram? ax.bar(names, heights) draws a bar of the height you give for each category, and does no counting. ax.hist(values) takes the raw values, bins them and counts. A bar chart shows a number per category (the accuracy of three models, the number of images per class); use a histogram for a continuous quantity.

Honest axes: bars start at zero

A bar encodes its value by its length, so the bar must start at zero. If the axis starts at 0.90, a bar for 0.93 is three times as long as a bar for 0.91, but the models differ by two percentage points. Lines and dots encode by position, so an axis that does not start at zero is acceptable for them (a loss curve does not need the zero), but for bars it is a distortion.

Run it: the same bars, two axes

Optional: runs real Matplotlib in your browser. The first run downloads about 19 MB (Python 6 MB, then Matplotlib with NumPy 13 MB), once; your browser keeps it (less if you already ran another Python cell on this site). The picture below is what the code draws.

Two bar charts of accuracy for model A (0.91, blue) and model B (0.93, reddish purple). On the left the y-axis runs from 0.90 to 0.94 and bar B is three times as tall as bar A. On the right the axis runs from 0 up to about 1 and the two bars are almost the same height.

The same two accuracies (0.91 for model A, 0.93 for model B, made up) drawn twice. On the left the y-axis runs from 0.90 to 0.94, so B's bar looks three times as long as A's. On the right it runs from 0 up to about 1 and the bars are almost equal. Both pictures contain the same numbers, and the labels above the bars give them.

Two more honesty habits. Compare on one scale: when two plots are meant to be compared, give them the same axis limits (sharey=True, or the same set_ylim), the same bins and, for images, the same vmin and vmax. Otherwise each plot stretches to fill its own box and a small thing can look as big as a large one. Say what the numbers are: label axes with the quantity and its unit, and write “made up” or the data source in the title or caption.

Images and matrices: imshow

ax.imshow(A) draws a 2-D array as a grid of coloured squares: one square per entry. That one function covers three jobs.

  • A grey-scale image. An array of shape (height, width), for instance a 28 by 28 digit. Row 0 is drawn at the top, like the rows of a matrix and of an image file.
  • A colour image. An array of shape (height, width, 3) (red, green, blue), with floats between 0 and 1 or integers between 0 and 255. Shape (height, width, 4) adds opacity. Other shapes such as (height, width, 2) give an error. (Images as tensors are the subject of P5.1.)
  • Any matrix as a heat map. A confusion matrix, an attention matrix, a correlation matrix, a weight matrix: the colour shows the size of each entry.

The settings that matter:

  • cmap is the colour map, the rule that turns a number into a colour. For a 2-D array the default is viridis, so a grey-scale photograph shows up in purple, green and yellow unless you say cmap="gray". A 3-D colour image ignores cmap.
  • vmin and vmax set which numbers get the lowest and the highest colour. By default they are the smallest and largest value of this array, so two images drawn with the defaults are not on a shared scale. Set them explicitly (vmin=0, vmax=255, or one vmin and vmax for both images) when you compare.
  • fig.colorbar(im, ax=ax) adds the key from colours to numbers. Here im is what imshow returned. A heat map without a colour bar is decoration.
  • origin is "upper" by default: entry [0, 0] is the top-left square. origin="lower" puts it at the bottom-left, which suits a plot of a function over a grid where y grows upward.
  • aspect defaults to "equal": squares stay squares. Use aspect="auto" for a very wide or tall matrix.
  • interpolation is how Matplotlib fills the space between squares when it resizes. With the default ("auto"), a small array drawn large gives sharp squares (what you want for a 5 by 5 array). Write interpolation="nearest" to make that certain.

Which colour map? Use viridis (the default sequential map) or another perceptually uniform one: equal steps in the number look like equal steps in colour, the map still reads in grey scale when printed, and it was designed to stay readable for the common forms of colour blindness. Avoid rainbow maps such as jet: they show bands and edges that are not in the data, and their lightness does not rise steadily with the value. For signed numbers (a gradient, a weight change, a correlation) use a diverging map such as "RdBu" with vmin=-m, vmax=m for one symmetric limit m, so that zero is the middle colour.

The next runner draws both jobs next to each other: a tiny 5 by 5 grey-scale image, and a confusion matrix with a colour bar and the counts written in the squares. A confusion matrix has one row per true class and one column per predicted class; the entry in row ii, column jj counts the examples of class ii that the classifier called jj. A perfect classifier has numbers only on the diagonal (P3.A9 explains the metrics built from it). These counts are made up: 150 images and 133 correct, so the accuracy is 133/150=0.887133/150=0.887.

Run it: imshow for an image and a matrix

Optional: runs real Matplotlib in your browser. The first run downloads about 19 MB (Python 6 MB, then Matplotlib with NumPy 13 MB), once; your browser keeps it (less if you already ran another Python cell on this site). The picture below is what the code draws.

Left: a 5 by 5 grey-scale image with a white upside-down T shape on black. Right: a 3 by 3 confusion matrix with classes cat, dog and bird, coloured with viridis. The diagonal squares read 48, 40 and 45 and are bright; the other squares read between 0 and 5 and are dark purple. A colour bar labelled count is on the right.

Left: a 5 by 5 grey-scale image drawn with cmap gray (0 is black, 1 is white). Right: a made-up confusion matrix for three classes with viridis colours, the counts written on the squares and a colour bar. The bright diagonal holds the correct predictions; the off-diagonal squares are the mistakes (for example, 5 true dogs were called cats).

Notice the line that picks the text colour: white on the dark squares and black on the bright ones, so every number stays readable. In the same way, ax.text(x, y, "words") writes at a data position and ax.annotate adds an arrow.

Grids of plots: subplots

plt.subplots(rows, cols) makes a Figure with a grid of Axes and returns the Figure and the Axes:

fig, axes = plt.subplots(2, 3, figsize=(9, 5))   # 2 rows, 3 columns, 6 Axes
axes[0, 1].plot(...)                             # row 0, column 1
for ax in axes.flat:                             # visit all six one after another
    ax.set_xlabel("epoch")

What axes is depends on the grid, which is a classic stumbling block:

Gridaxes isPick one Axes
plt.subplots() (1 by 1)a single Axes, not an arrayuse it directly
plt.subplots(1, 3) or plt.subplots(3, 1)a 1-D array of 3axes[2]
plt.subplots(2, 3)a 2-D array of shape (2, 3)axes[1, 2]

Unpacking is only convenient when you know the grid: fig, (ax1, ax2) = plt.subplots(1, 2). To treat all cases the same, pass squeeze=False (you always get a 2-D array) and use axes.flat. Other settings you will use:

  • sharex=True, sharey=True give all plots one x-axis or y-axis scale, and show the tick labels only on the outer plots. Use them whenever the panels are to be compared (the histogram runner above does).
  • figsize=(width, height) is in inches for the whole Figure. A phone-friendly picture is narrow, such as (4.5, 3).
  • fig.tight_layout() (or the setting layout="constrained" in plt.subplots, a newer and often better layout engine) stops titles and labels from overlapping.
  • fig.suptitle("...") puts one title over the whole Figure. A grid is also the usual way to plot one training curve per metric (loss, accuracy) or one image per class.

Labels, legends, limits and ticks

Every plot you show someone needs the same few lines. A plot without them is a puzzle.

ax.set_xlabel("epoch")                 # what the x-axis is (add units: "time (s)")
ax.set_ylabel("loss")                  # what the y-axis is
ax.set_title("Training loss")          # what the whole plot is
ax.legend()                            # needed when there are two or more labelled series
ax.set_xlim(0, 40)                     # axis range (also ax.set_ylim(low, high))
ax.set_yscale("log")                   # or "linear"
ax.grid(True, alpha=0.3)               # faint grid lines, easier to read values
ax.axhline(0.5, color="gray", linestyle=":")   # a horizontal reference line (axvline for vertical)
ax.set(xlabel="epoch", ylabel="loss")  # several setters in one call

ax.legend() only lists artists that have a label. If you forget the label= in the plot call, you get a warning and an empty legend. Matplotlib puts the legend where it overlaps least; loc="upper right" places it by hand.

Saving a figure

fig.savefig("loss.png", dpi=150, bbox_inches="tight")   # raster image for slides, web and reports
fig.savefig("loss.pdf")                                  # vector, for a paper: sharp at any zoom
fig.savefig("loss.svg")                                  # vector, for the web
plt.close(fig)                                           # free the memory when you are done with it

The file type comes from the extension. The picture is figsize times dpi pixels: figsize=(4.5, 3) with dpi=150 is a 675 by 450 pixel PNG. bbox_inches="tight" trims the white margin and makes sure that no label is cut off, which changes the final size slightly. Use transparent=True for a transparent background (take care: black text on a transparent picture disappears on a dark page). Vector formats (PDF, SVG) store the shapes and stay sharp at any size, and are the better choice for papers. Raster formats (PNG) store pixels and are good for photographs and very busy plots.

Save before plt.show() in a script: after you close the window the figure may be gone, and a later savefig can write an empty picture. In a loop that makes many figures, call plt.close(fig) after saving each one: Matplotlib keeps every open figure in memory and warns after 20.

Notebook, script or server: where does the plot appear?

  • In a notebook (Jupyter, Colab): the figure appears under the cell by itself. Use plt.show() at the end if you want to be explicit.
  • In a plain script run from the command line: nothing appears until you call plt.show(), which opens a window and waits until you close it. Forgetting it is the most common “my script plots nothing” problem.
  • On a server without a screen: use fig.savefig("name.png") and open the file. Matplotlib then needs a backend that draws into memory, called Agg.
  • On this page, the runners use Agg and show the result under the code, so plt.show() does nothing here (it is safe to leave it in). The runner shows the current figure (plt.gcf()), the last one you created. It also sets figure.dpi to 110 and the font size to 12 before your code runs, so that text stays readable when the picture shrinks to a phone screen.

Common mistakes

  1. Missing labels and units. The plot makes sense to you, today. Add set_xlabel, set_ylabel, a title and a legend.
  2. Wrong array shape. ax.plot(x, y) wants x and y to have the same length. A column of shape (n, 1) works (it is one line), and a 2-D array of shape (n, 3) draws three lines, one per column. But a row of shape (1, n) is read as n lines of one point each, which draw nothing you can see, and ax.plot(x, y_row) raises an error about the first dimension. Check y.shape, and flatten with y.ravel(). The same shape trap breaks masks: with labels of shape (n, 1), the mask y == k is 2-D and X[y == k, 0] fails, so use y.ravel() first.
  3. plt.title after several Axes. It titles the current Axes, not the one you meant. Use ax.set_title.
  4. Unsorted x in a line plot. plot joins the points in the order you give them, so unsorted x gives a zigzag. Sort first (np.argsort) or use scatter.
  5. NaN values. A nan in y leaves a gap in the line. That is usually what you want, and surprising if you did not know. A loss that turned nan shows up as a line that stops.
  6. A grey-scale image in the wrong colours. ax.imshow(img) for a 2-D array uses viridis. Pass cmap="gray".
  7. A forgotten plt.show() in a script, or savefig after show (see “Saving a figure”).
  8. Many figures left open in a loop (see “Saving a figure”).
  9. Colour as the only signal, and truncated or different axes (see “Honest axes”).

What Matplotlib is not

Matplotlib is low-level: you say every detail. Other tools build on it or replace it: pandas draws a plot from a table with one call, df.plot() (P2.5), seaborn draws statistical plots such as grouped histograms and heat maps with better defaults, and Plotly draws interactive plots in a browser. They are out of scope here. Training tools that live in a browser tab (TensorBoard, or the dashboards of experiment trackers, P12.3) show the same loss curves while a model trains. The objects from this lesson, a Figure with Axes, are what you meet whenever any of these tools hands you a plot to adjust.

Intuition

A Figure is a sheet of paper, and each Axes is a framed picture glued onto it. plt.subplots(2, 3) buys a sheet with six empty frames. You do not paint on the sheet: you paint inside a frame (ax.plot), and write on the frame’s border (ax.set_xlabel). A log axis is a ruler where every step is “times ten” instead of “plus ten”. A histogram is a row of buckets: you choose how wide each bucket is, and the picture is how many values fell into each one. The analogy breaks at the pyplot shortcuts: there Matplotlib guesses which frame you meant, and it guesses the last one you touched.

Math

Log axis. A loss that decays as y=ae−kty=ae^{-kt} has log⁡y=log⁡a−kt\log y=\log a-kt, a straight line in tt with slope −k-k. On a log axis the vertical position of a value is proportional to log⁡y\log y, so a ratio y1/y2y_1/y_2 always takes the same distance, wherever it occurs. That is why a straight line on a log axis means exponential decay, and why a curve that flattens out on it means the decay is slowing.

Histogram density. For nn values and bin jj with count cjc_j and width wjw_j, density=True draws the height hj=cjn wj,h_j=\frac{c_j}{n\,w_j}, so the area of bar jj is hjwj=cj/nh_jw_j=c_j/n, the share of the data in that bin, and the areas add up to ∑jcj/n=1\sum_j c_j/n=1. For the data above with 8 bins of width 10 the heights are 0, 0.0133, 0.0333, 0, 0.0183, 0.03, 0.005 and 0.

Image size. A figure of figsize=(W, H) inches saved at dd dots per inch has WdW d by HdH d pixels: 4.5×150=6754.5\times150=675 and 3×150=4503\times150=450.

Code

A reusable recipe: a function that draws on an Axes you pass in, so you can place it in any grid.

import numpy as np
import matplotlib.pyplot as plt

def plot_curves(ax, history, title):
    """history: dict of name -> list of numbers. Draws on the Axes you give it."""
    for name, values in history.items():
        ax.plot(values, label=name)
    ax.set_title(title)
    ax.set_xlabel("epoch")
    ax.legend()

history = {"train": [1.0, 0.5, 0.3, 0.2], "val": [1.1, 0.7, 0.5, 0.5]}
fig, axes = plt.subplots(1, 2, figsize=(7, 3))
plot_curves(axes[0], history, "linear")
plot_curves(axes[1], history, "log")
axes[1].set_yscale("log")
fig.tight_layout()
fig.savefig("curves.png", dpi=150, bbox_inches="tight")

Pass the Axes in and the function works for a single plot or for a cell in a grid. The same shape (ax as the first argument) is what libraries such as pandas and seaborn use.

Go deeper Two y-axes, and why to be careful

ax2 = ax.twinx() makes a second Axes that shares the x-axis and has its own y-axis on the right, so one plot can show a loss (left) and an accuracy (right). It is handy and easy to abuse: the two scales are unrelated, so you can make two lines cross anywhere by choosing the limits. When you can, draw two panels with sharex=True instead, and if you use twinx, colour each y-axis label like its line.

Go deeper Colour normalization: LogNorm and TwoSlopeNorm

vmin and vmax map numbers to colours linearly. A norm changes that rule. matplotlib.colors.LogNorm() spaces colours by the logarithm, useful for a matrix with values from 0.001 to 1000 (it needs positive values). TwoSlopeNorm(vcenter=0) (from matplotlib.colors) puts a chosen number, such as zero, at the middle of a diverging map even when the data range is not symmetric. You pass one to imshow as norm=... instead of vmin and vmax. Both change what the colours mean, so keep the colour bar and say so.

Go deeper Backends, the pyplot state machine and layouts

A backend is the part of Matplotlib that turns a Figure into something you see or save. Window backends (such as Qt or Tk) show an interactive window, notebook backends show the figure in the cell, and Agg draws into memory, which suits a program with no screen and is what the runners on this page use. Pyplot keeps a global list of open figures and a “current” one and Axes inside it; plt.gcf() and plt.gca() return them. That global state is what makes plt.plot work without a variable, and why it misbehaves when you juggle several plots.

For layouts, plt.subplot_mosaic([["a", "b"], ["c", "c"]]) makes a grid where one plot spans two cells and returns the Axes by name, and layout="constrained" places colour bars and labels without overlaps more reliably than tight_layout.

Try it

The five runnable plots above are the activity of this lesson: run each one, then change one thing and run it again. Here are some changes to try, one for each plot.

  1. Loss curves. Delete the ax.set_yscale("log") line. Which of the two curves becomes hard to read? Change the 0.012 * epochs term in val to 0.005 * epochs: where does the best epoch move?
  2. Scatter. Set alpha=1 and s=60. What can you no longer see? Then move class 1’s mean from [3.2, 3.0] to [5.0, 5.0]: how do the clouds change?
  3. Histogram. Edit bins_to_try to [8, 10, 12]. Does the gap between the two groups appear at all three? Then add density=True to the ax.hist call and read the new y-axis.
  4. Bars. Change ax1.set_ylim(0.90, 0.94) to ax1.set_ylim(0.909, 0.931). How many times taller does model B look now?
  5. imshow. Change cmap="viridis" to cmap="jet". Do the bright and dark bands match the sizes of the numbers? Then change cmap="gray" for the image to cmap="viridis".

Check your understanding

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

  2. You call fig, axes = plt.subplots(1, 4). How do you draw on plot number 3, counting from 1?

  3. A training loss falls from 2.0 to 0.002 over 100 epochs. Why is ax.set_yscale("log") a good choice?

  4. You draw ax.hist(x, bins=8, range=(0, 80), density=True) for 60 values, and 8 of them fall in the bin from 10 to 20. What is the height of that bar?

  5. A bar chart shows accuracy 0.91 for model A and 0.93 for model B on a y-axis that runs from 0.90 to 0.94, and B's bar is three times as tall as A's. What is wrong?

  6. You draw a 28 by 28 grey-scale digit with ax.imshow(img) and see a purple and yellow picture. What is the likely reason and the fix?

Exercises

  1. Write the lines that draw y=x2y=x^2 for 50 points of xx between −3-3 and 33 in the Figure-and-Axes style, with labels for both axes and a title.
    Show answerx = np.linspace(-3, 3, 50), then fig, ax = plt.subplots(), ax.plot(x, x**2), ax.set_xlabel("x"), ax.set_ylabel("y = x squared") and ax.set_title("A parabola"). Every drawing and label is a method on ax.
  2. x = np.arange(5) and y = np.array([[1, 2, 3, 4, 5]]) (shape (1, 5)). What do ax.plot(y) and ax.plot(x, y) do, and how do you fix them?
    Show answerax.plot(y) reads the array as 5 columns, so it draws 5 lines of one point each, which are invisible with the default style. ax.plot(x, y) raises a ValueError because x has shape (5,) and y has shape (1, 5). Use y.ravel() (shape (5,)) or y[0], then ax.plot(x, y.ravel()) draws one line.
  3. For the 60 values of the histogram runner, with bins=8 and range=(0, 80) the counts are [0, 8, 20, 0, 11, 18, 3, 0]. What are the heights with density=True, and what is the total area?
    Show answerEach height is the count divided by 60×10=60060\times10=600, so the heights are 0, 0.0133, 0.0333, 0, 0.0183, 0.03, 0.005 and 0. The total area is the sum of the heights times the width 10, which is (8+20+11+18+3)/60=1(8+20+11+18+3)/60=1. The heights themselves add to 0.1.
  4. fig, axes = plt.subplots(2, 3). What is axes.shape, how do you pick the plot in the second row and third column, and how do you loop over all six?
    Show answerThe shape is (2, 3). The plot in the second row and third column is axes[1, 2], since counting starts at 0. for ax in axes.flat: visits all six, row by row.
  5. You save fig.savefig("a.png", dpi=150) for a figure made with figsize=(4.5, 3). How many pixels wide and high is the file? What changes if you add bbox_inches="tight"?
    Show answer4.5×150=6754.5\times150=675 pixels wide and 3×150=4503\times150=450 high. With bbox_inches="tight" the white margins around the plot are trimmed, so the file comes out a little smaller than 675 by 450 (for a simple line plot with axis labels, about 609 by 439); the exact size depends on the labels.
  6. A loss is 3.0, 0.3, 0.03 and 0.003 at epochs 1 to 4. On a linear y-axis from 0 to 3, how high is the last point, and what does a log axis show instead?
    Show answerOn the linear axis the last point is at 0.003/3=0.1%0.003/3=0.1\% of the height, so it sits on the axis and looks like zero, and the third point is at 1%1\%. On a log axis each value is ten times smaller than the one before, so the four points are equally spaced and fall on a straight line.
  7. A 28 by 28 array img of integers between 0 and 255 is a grey-scale photo. Write the imshow call that shows it correctly with a colour bar, and say what vmin=0, vmax=255 guarantees.
    Show answerim = ax.imshow(img, cmap="gray", vmin=0, vmax=255) and fig.colorbar(im, ax=ax). Fixing vmin and vmax makes 0 always black and 255 always white. Without them the darkest value in this image is drawn black and the brightest white, even if the image is dim, so two images could not be compared.
  8. You plot training and validation accuracy and the figure will be printed in black and white. How do you keep the two lines distinguishable?
    Show answerDo not rely on colour. Give the lines different line styles and markers, such as linestyle="-", marker="o" and linestyle="--", marker="s", give each a label and call ax.legend(). Colours from a colour-blind-safe set (for example blue and reddish purple as in this lesson) can stay as an extra signal.

Next: P2.5 loads and cleans tables of data with pandas, whose df.plot() draws these same plots from a column in one line. P3.A9 turns the confusion matrix into precision and recall, and P4.22 shows what each loss-curve shape means.

Key takeaways

  • A Figure is the whole canvas. An Axes is one plot on it: the box with its data, ticks, labels and title. Use fig, ax = plt.subplots() and call methods on ax (ax.plot, ax.set_xlabel). The pyplot shortcuts (plt.plot) act on a hidden “current” Axes, which is fine for a quick look and a source of confusion once you have several plots.
  • Line plot ax.plot(x, y) for a curve over an ordered x such as an epoch. If you give only y, the x values are 0, 1, 2, .... Losses span orders of magnitude, so ax.set_yscale('log') gives equal vertical distance to equal ratios. A rising validation curve while the training curve falls is the picture of overfitting.
  • Scatter ax.scatter(x, y) draws one dot per example. Colour by class (and change the marker too), use alpha and a small s when points overlap. Histogram ax.hist(x, bins=...) counts values per bin: the number of bins changes the picture, so try several. density=True makes the total area 1, which is what lets you compare groups of different sizes.
  • imshow draws a 2-D array as a coloured grid (a matrix, a confusion matrix, a grey-scale image) or a 3-D array of shape height, width, 3 as a colour image. A 2-D array uses a colour map: pass cmap='gray' for a photograph, add fig.colorbar, and set vmin and vmax when two pictures must share one scale. Prefer perceptually uniform maps such as viridis to rainbow ones.
  • plt.subplots(rows, cols) returns an array of Axes (one Axes if 1 by 1, a 1-D array if one row or one column, a 2-D array otherwise). sharex and sharey give plots one scale. Save with fig.savefig('name.png', dpi=150, bbox_inches='tight'); use PDF or SVG for vector output. In a script plt.show() opens the window, in a notebook the figure appears by itself, and on a server you save the file.
  • Plots can lie. Bars must start at zero. Use the same scale to compare panels. Label axes with units and put a legend on every plot with more than one series. Do not rely on colour alone (add markers or line styles) and avoid red against green. Check the shape of your arrays: a row vector of shape (1, n) plots as n one-point lines, which you cannot see.
Found a mistake? Tell us