Plotting with matplotlib
Last updated
You can't see a pattern in 342 rows of numbers, but you can see it in a plot, and you'll read plots in every lesson from here on: loss curves to tell whether a model is learning, scatter plots to see whether classes can be told apart, histograms to spot a feature on the wrong scale. In this lesson you'll draw those three with matplotlib, put several in one figure, and label them so they still make sense next week.
By the end of this lesson you can
- Draw a line plot, a scatter plot and a histogram with matplotlib
- Put several plots side by side in one figure with
plt.subplots - Label axes, add a title and a legend
- Read a loss curve: what going down, and flattening, mean
A loss curve
The plot you'll look at most in this course is the loss curve: how wrong a model is (its loss) after each step of training. Here's one. The numbers are made up to have the usual shape; Stage 3 makes real ones. Run it; the first run takes a few seconds while matplotlib loads.
The pattern for every plot in this course:
fig, ax = plt.subplots()makes a figure (the whole picture) and one axes (the box you draw in, with its x- and y-axis).ax.plot(steps, loss)draws a line through the points: step 0 against loss 2.15, step 1 against 1.85, and so on.ax.set_xlabel,ax.set_ylabelandax.set_titlesay what's being shown.plt.show()displays it.
Reading it: the loss falls fast at first, then more and more slowly, and flattens out just above 0.15. A falling curve means the model is learning; a flat one means it has stopped improving. In Stage 3 you'll see curves that go up, and learn what they mean.
plt is short for matplotlib.pyplot, the part of matplotlib you import. Everyone writes import matplotlib.pyplot as plt.
Scatter plots and histograms
Now real data: flipper length and body mass of penguins from Palmer Station in Antarctica, measured by Kristen Gorman and colleagues (2014) and shared freely. The first cell loads two columns of penguins.csv with np.genfromtxt, which reads the text NA as nan (not a number), then keeps only the rows with no nan. That line is a mask, as in lesson 0.3: np.isnan marks each missing value, .any(axis=1) asks of each row whether it has one (lesson 0.4), and ~ turns True into False and back, so the mask is True for complete rows. Run all three cells:
data.shapeis(342, 2): two of the 344 penguins had no measurements and were dropped.ax.scatter(flipper, mass)draws one dot per penguin: flipper length across, mass up. The dots rise from left to right, so the two features go together: longer flippers, heavier penguins. A model predicting mass from flipper length (Stage 3 builds one) has something to find.s=10makes the dots small so they don't hide each other.ax.hist(mass, bins=20)splits the range of masses into 20 equal bins and draws how many penguins fall in each. The masses run from 2,700 g to 6,300 g. The tallest bars are between about 3,200 and 4,000 g, and there's a long, lower stretch of heavier birds out to the right. Lesson 0.P shows where those heavier birds come from.
Scatter plots are how you'll see whether classes can be separated, and histograms how you'll check a feature's range before training.
Several plots in one figure
plt.subplots(1, 2) makes one figure with 1 row and 2 columns of axes. You get the axes back as a pair, and draw on each:
figsize=(9, 3.5)sets the figure's width and height in inches, so two plots fit side by side.leftandrightare two axes; each gets its ownhist, labels and title.color="tab:orange"picks a colour from matplotlib's standard set.fig.tight_layout()moves the plots apart so their labels don't overlap.
With plt.subplots(2, 2), you'd get a 2 × 2 grid as an array of axes, used as axes[0, 1]: the indexing from lesson 0.3. The project at the end of this stage draws four plots that way.
Wrong way: a plot with no labels
You train two models and plot both loss curves, quickly, to compare. Run the first cell:
Today you remember that the blue line is the first run and the orange one the second, and what the y-axis is. Next week you won't. Is the y-axis loss, or accuracy? (For accuracy, higher is better: the opposite reading.) Which colour was which learning rate? Was this the training data or the test data? The first plot can't answer any of that, and there's no error to warn you.
The second cell is the same data with:
- axis labels that say what's measured, and on what data,
label=on each line andax.legend()to show which is which,- a title.
Make it a habit: no plot leaves your notebook without labels. When you compare runs, put what you changed in the legend. You'll thank yourself in Stage 7, where a single experiment can mean a dozen curves.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- matplotlib: Quick start guide: figures and axes, the explicit interface, labels and legends
- matplotlib: matplotlib.pyplot.subplots: a figure with a grid of axes
- matplotlib: matplotlib.axes.Axes.scatter: scatter plots
- matplotlib: matplotlib.axes.Axes.hist: histograms
- NumPy: numpy.isnan: finding the missing values that genfromtxt reads as nan
- Gorman, Williams and Fraser, Ecological Sexual Dimorphism and Environmental Variability within a Community of Antarctic Penguins, PLOS ONE 9(3), 2014: where the penguin measurements come from
- Horst, Hill and Gorman, palmerpenguins: Palmer Archipelago (Antarctica) penguin data, 2020: the penguins dataset, released under CC0