Python for data · lesson 8 of 11
Parts in this lesson
Afig, ax = plt.subplots()a figure, and one set of axes to draw on
Bax.plot(x, y)a line: values that follow on
Cax.scatter(x, y)dots: two features of each example
Dax.hist(values, bins=20)how one feature is spread out
Eax.set_xlabel("…")labels, a title and a legend

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.

loss.ipynb

The pattern for every plot in this course:

  1. fig, ax = plt.subplots() makes a figure (the whole picture) and one axes (the box you draw in, with its x- and y-axis).
  2. ax.plot(steps, loss) draws a line through the points: step 0 against loss 2.15, step 1 against 1.85, and so on.
  3. ax.set_xlabel, ax.set_ylabel and ax.set_title say what's being shown.
  4. 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:

penguins.ipynb
  • data.shape is (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=10 makes 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:

penguins.ipynb
  • figsize=(9, 3.5) sets the figure's width and height in inches, so two plots fit side by side.
  • left and right are two axes; each gets its own hist, 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:

runs.ipynb

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 and ax.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

You want to see whether two features of the same penguins go together. Which plot?
A loss curve falls quickly for 20 steps, then stays flat for the next 200. What does it tell you?
Predict, then change step 3’s notebook to check: with fig, axes = plt.subplots(2, 3), what is axes.shape?

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.

All sources for Simple Machine Learning