Section 1

1 Before you start

This is not graded, and it does not count towards anything. Answer every question even if you are only guessing — having a go at something before you have been taught it is one of the best ways to remember it afterwards. The lesson ends with another short check, and there you will be shown the correct answer for anything you missed. Choose an option for every question and confidence rating, then click Submit answers.

Pre-test

You write a Python script that ends with plt.plot(ages) and run it. The script finishes without errors but no figure window appears on screen. What is the most likely cause?

Pre-test

You write fig, ax = plt.subplots() and want to draw a line on that panel using the object-oriented style. Which call is correct?

Pre-test

You plot age (x) against BMI (y) for 200 unrelated patients and join the points with plt.plot. Why is the result misleading?

Pre-test

You have one row per patient in a DataFrame and want to show the relationship between age and cholesterol. Which matplotlib call is the right one?

Pre-test

You want to compare two patients' weight trajectories on the same axes. What is the simplest correct approach?

Pre-test

You want to see the distribution of patient ages across your study. Which call produces the right plot?

Pre-test

You have the mean BMI for each of three clinics (A, B, C) and want to compare them. Which call is the right one?

Pre-test

You draw plt.hist(values, bins=3) on several hundred measurements and the distribution looks like a featureless block. What is the most sensible next step?

Pre-confidence

I can decide whether a particular plot should be a line plot, a scatter plot, a bar plot, or a histogram, and explain why.

Not at all confident
Fully confident
Pre-confidence

I can set up a matplotlib figure in either the pyplot or the object-oriented style, follow the import-build-show skeleton, and plot one or more series on the same axes.

Not at all confident
Fully confident
Section 2

2 Introduction

A column of ages or a list of expression values means little until you plot it. A histogram shows how the ages spread out. A bar chart shows which gene has the highest expression.

Matplotlib is the plotting library that the pandas method df.plot() and seaborn build on. This lesson covers how to set up a figure, two ways to code it, the line, scatter, bar and histogram plots, and error bars. The next lesson covers labels, legends, subplots and saving figures.

Introduction to the eight plot types you can create with matplotlib.
Introduction to the eight plot types you can create with matplotlib.

Try every example in the Python Scratchpad on the right.

Section 3

3 Introduction to Matplotlib

Matplotlib is a third-party package. The convention is to import its pyplot module under the alias plt. After that line, you call every plotting tool as plt.something.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import matplotlib.pyplot as plt

ages = [54, 61, 47, 72, 38, 65, 49]
plt.plot(ages)
plt.show()

plt.plot draws one line through the seven ages. plt.show() displays the figure. In the Scratchpad, the figure appears as a thumbnail in the Graph tab. Click the thumbnail to open it.

NOTE: Without plt.show(), no figure appears in the Graph tab. In a plain Python script, no window opens. Jupyter notebooks usually show figures without it.

Section 4

4 The Canvas vs The Plot

Matplotlib manages two kinds of object behind the scenes:

  • A Figure is the whole canvas, the window that holds everything.
  • An Axes is the plotting area inside the figure, the box that holds your data, tick marks and labels.

A single Figure can hold several Axes, which are also called subplots. A call to plt.plot creates one of each automatically.

A Figure is the outer container; an Axes is a plotting region inside it, and one Figure can hold many Axes as subplots.
A Figure is the outer container; an Axes is a plotting region inside it, and one Figure can hold many Axes as subplots.

The next example makes one Figure with two Axes side by side. In plt.subplots(1, 2), the numbers mean one row and two columns.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(1, 2)
fig.suptitle("One Figure (the whole window)")
ax1.set_title("Axes 1 (a panel inside)")
ax2.set_title("Axes 2 (another panel)")
ax1.plot([1, 2, 3], [1, 4, 9])
ax2.plot([1, 2, 3], [3, 2, 1])
plt.show()
Section 5

5 Two Ways to Code

You will meet two styles of writing Matplotlib code:

  • The pyplot style is a series of plt.something calls on the current figure. It is short and suits quick plots.
  • The object-oriented style first creates the figure and the axes. Then it calls methods on the axes. It suits figures with several panels.

Here are the two styles:

(a) pyplot style

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import matplotlib.pyplot as plt

ages = [54, 61, 47, 72, 38, 65, 49]
plt.plot(ages)
plt.show()

(b) Object-oriented style

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([54, 61, 47, 72, 38])
plt.show()
A side-by-side comparison of matplotlib's pyplot style, where plt holds the figure state internally, and the object-oriented style, where fig and ax are named variables the programmer can reference directly.
A side-by-side comparison of matplotlib's pyplot style, where plt holds the figure state internally, and the object-oriented style, where fig and ax are named variables the programmer can reference directly.

NOTE: The call plt.subplots() with no arguments returns a tuple of two objects: one Figure and one Axes. If you store the result under one name, that name holds the whole tuple. So the plot call fails:

import matplotlib.pyplot as plt

ax = plt.subplots()
ax.plot([54, 61, 47])
# AttributeError: 'tuple' object has no attribute 'plot'

Store the two objects in two names, such as fig and ax. Then ax holds the Axes. Named axes help most when a figure has several panels, as the next animation shows.

Object-oriented style scales to many subplots: pyplot tracks one implicit active subplot at a time, while named ax[i] variables let the programmer target any panel directly.
Object-oriented style scales to many subplots: pyplot tracks one implicit active subplot at a time, while named ax[i] variables let the programmer target any panel directly.
Section 6

6 The Three-Step Skeleton

Every plot in this lesson follows the same three steps:

  • Import Matplotlib
  • Build the plot with pyplot or object-oriented calls
  • Show (or savefig) the final output
# The three-step skeleton every plot follows.
import matplotlib.pyplot as plt # 1. import

plt.plot([54, 61, 47, 72, 38]) # 2. build (one or more pyplot calls)
plt.xlabel("Patient index")
plt.ylabel("Age")

plt.show() # 3. show (or .savefig for a file)
Three-step matplotlib rhythm, showing how plotting calls accumulate before being rendered when plt.show() runs.
Three-step matplotlib rhythm, showing how plotting calls accumulate before being rendered when plt.show() runs.

Every plot so far has used the default look of Matplotlib. The call plt.style.use("ggplot") changes the look in one line. It swaps in different colours, background shading and grid lines for every later plot. To see all the built-in styles, run print(plt.style.available).

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import matplotlib.pyplot as plt

plt.style.use("ggplot")

ages = [54, 61, 47, 72, 38, 65, 49]
plt.plot(ages)
plt.show()

The call plt.style.use() is a global setting for the rest of the session. Call it once, near the top of your script, right after the import. Every plot you draw afterwards uses the new look, even a plot on a different topic. To go back, call plt.style.use("default").

Section 7

7 Choosing your plot

Each of the four basic plots answers a different question about your data. The question decides which plot to use:

  • Line plots ask: How does this change over an ordered sequence (like time)?
  • Scatter plots ask: Is there a relationship between these two variables?
  • Bar plots ask: How does a summary metric compare across distinct categories?
  • Histograms ask: How are the values distributed within a single dataset?
Four common plot types and the question each one is designed to answer.
Four common plot types and the question each one is designed to answer.
Section 7.1

7.1 plt.plot for line plot

plt.plot is the line tool. It takes x values and y values. It draws a line that joins the points in order. With only one list, Matplotlib uses the index numbers 0, 1, 2 and so on as the x values.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import matplotlib.pyplot as plt

months = [0, 1, 2, 3, 6, 12]
weight_kg = [82.0, 80.5, 79.1, 77.8, 75.4, 73.2]

plt.plot(months, weight_kg)
plt.show()

This plot shows the weight of one patient over a year. The weight falls from 82.0 kg to 73.2 kg. The line gets flatter towards the end. So the weight falls more slowly in the later months. Line plots suit an x-axis that has an order, such as time, dose or position along a chromosome.

Each x value pairs with one y value. So the two lists need the same length. In the next example, the last weight is missing. So Matplotlib raises a ValueError:

import matplotlib.pyplot as plt

months = [0, 1, 2, 3, 6, 12]
weight_kg = [82.0, 80.5, 79.1, 77.8, 75.4]

plt.plot(months, weight_kg)
# ValueError: x and y must have same first dimension, but have shapes (6,) and (5,)
plt.plot pairs x and y values by index and connects the points in order, with a side-by-side terminal and matplotlib-style chart.
plt.plot pairs x and y values by index and connects the points in order, with a side-by-side terminal and matplotlib-style chart.
Section 7.2

7.2 plt.scatter for scatter plots

plt.scatter is the dot tool. It draws one dot for each pair of x and y values, with no line between the dots. Use it when each point is a separate case, such as one point for each patient. A line would join each patient to the next one in the list. That link does not exist.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import matplotlib.pyplot as plt

ages = [54, 61, 47, 72, 38, 65, 49, 58, 71, 44]
bmi = [27.3, 24.1, 31.2, 22.8, 29.5, 26.0, 30.1, 25.4, 23.7, 28.2]

plt.scatter(ages, bmi)
plt.show()

Each dot is one patient. In these ten patients, the older patients tend to have a lower BMI. The next example uses plt.plot on the heights and weights of ten patients, listed in no particular order.

import matplotlib.pyplot as plt

height_cm = [165, 152, 177, 158, 171, 163, 180, 160, 169, 175]
weight_kg = [66, 52, 78, 58, 72, 62, 85, 57, 68, 76]

plt.plot(height_cm, weight_kg)
plt.show()

The line jumps back and forth. This is because it joins the patients in the order of the list. That order has no meaning. Replace plt.plot with plt.scatter. Then the dots show that the taller patients tend to weigh more.

How plt.scatter places one dot per (x, y) pair, contrasting the clean cloud with the chaotic line plt.plot would draw through unsorted data, then highlighting the underlying trend.
How plt.scatter places one dot per (x, y) pair, contrasting the clean cloud with the chaotic line plt.plot would draw through unsorted data, then highlighting the underlying trend.

With hundreds of points, the markers pile up on top of each other. The cloud turns into a solid blob. The alpha= argument fixes this. It sets how see-through each marker is, from 0 (invisible) to 1 (fully solid). Where markers overlap, the layers add up. So a crowded area looks darker than a single marker.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(seed=1)
ages = rng.normal(55, 12, 500)
bmi = rng.normal(27, 4, 500)

plt.scatter(ages, bmi, alpha=0.3)
plt.show()
Section 7.3

7.3 Plotting multiple series

A series is one set of points to draw. To draw more than one series on the same axes, call plt.plot or plt.scatter once for each series. Matplotlib gives each series its own colour. So you can tell them apart.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import matplotlib.pyplot as plt

months = [0, 3, 6, 12]
patient_a = [82, 79, 75, 73]
patient_b = [78, 76, 75, 74]

plt.plot(months, patient_a)
plt.plot(months, patient_b)
plt.show()

The two lines share one scale. So you can compare them directly.

Calling plt.plot twice draws two auto-colored lines on the same axes, allowing direct comparison of two series at a glance.
Calling plt.plot twice draws two auto-colored lines on the same axes, allowing direct comparison of two series at a glance.
Section 7.4

7.4 plt.bar for bar plots

plt.bar takes a list of categories for the x-axis and a list of heights for the y-axis. The heights are usually a summary of the data, such as a mean or a percentage.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import matplotlib.pyplot as plt

clinics = ["A", "B", "C"]
mean_bmi = [27.4, 25.1, 29.0]

plt.bar(clinics, mean_bmi)
plt.show()

If the category names are long, they overlap on the x-axis. The function plt.barh draws horizontal bars. The names then run down the y-axis, where they have room:

import matplotlib.pyplot as plt

departments = ["Cardiology", "Endocrinology", "Gastroenterology"]
beds = [30, 24, 28]

plt.barh(departments, beds)
plt.show()
How plt.bar pairs each category with its summary height and raises a bar for each.
How plt.bar pairs each category with its summary height and raises a bar for each.
Section 7.5

7.5 plt.hist for historgrams

A histogram groups the numbers in one list into ranges of equal width, called bins. The function plt.hist draws one bar for each bin. Each bar is as tall as the number of values in its bin.

import matplotlib.pyplot as plt

heart_rate = [60, 62, 64, 65, 66, 67, 68, 69, 70, 70, 71, 72, 73, 74, 75, 77, 79, 82, 86, 90]

result = plt.hist(heart_rate, bins=5)
print(result[0])  # [4. 7. 5. 2. 2.]
print(result[1])  # [60. 66. 72. 78. 84. 90.]
plt.show()

coarse = plt.hist(heart_rate, bins=2)
print(coarse[0])  # [14.  6.]
plt.show()

The list holds the resting heart rates of 20 patients, in beats per minute. plt.hist returns a tuple. Its first item holds the counts. Its second item holds the bin edges. Five equal bins cover 60 to 90. The second bin, from 66 to 72, holds the most patients: 7. With only two bins, the counts are 14 and 6. The peak between 66 and 72 no longer shows. The Graph tab shows both figures.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import matplotlib.pyplot as plt

ages = [54, 61, 47, 72, 38, 65, 49, 58, 71, 44, 60, 55, 67, 41, 50]

plt.hist(ages, bins=8)
plt.show()

The bins= argument sets how many bars the histogram has. Too few bins hide the shape of the data. Too many bins leave most bars with one value or none. There is no single right number. Try a few, and keep the one that shows the shape clearly. If you leave out bins=, Matplotlib uses 10.

plt.hist showing fifteen values flying into equal-width buckets to form a histogram, then tuning the bins argument through several values to compare how the shape changes.
plt.hist showing fifteen values flying into equal-width buckets to form a histogram, then tuning the bins argument through several values to compare how the shape changes.

By default, histogram bars touch each other with no border. Neighbouring bars of similar height can blend into one shape. The edgecolor="white" argument draws a thin white line around every bar. This keeps the bars apart.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import matplotlib.pyplot as plt

ages = [54, 61, 47, 72, 38, 65, 49, 58, 71, 44, 60, 55, 67, 41, 50]

plt.hist(ages, bins=8, edgecolor="white")
plt.show()
Section 7.6

7.6 plt.errorbar for adding uncertainty

A bar plot of group means hides how much the data in each group vary. plt.errorbar draws each mean with a vertical line through it, called an error bar. The line can show a standard deviation, which is the spread of the data. Or it can show a standard error of the mean (SEM) or a 95% confidence interval, which measure how precise the mean is. The yerr argument sets how far the line reaches above and below each mean. It takes one number for every mean, or a list with one number per mean.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import matplotlib.pyplot as plt

clinics = ["A", "B", "C"]
mean_bmi = [27.4, 31.1, 24.8]
sem = [0.8, 1.1, 0.6]
plt.errorbar(clinics, mean_bmi, yerr=sem, fmt="o", capsize=5)
plt.ylabel("Mean BMI (with SEM)")
plt.title("BMI by clinic")
plt.show()

The fmt="o" argument draws each mean as a dot. Without it, plt.errorbar joins the means with a line. A line between separate groups has no meaning. The capsize=5 argument adds a short cap to both ends of each error bar. The first error bar runs from 26.6 to 28.2. This is the mean, 27.4, plus and minus the SEM, 0.8.

plt.errorbar adds vertical whiskers to mean values, then compares how the choice of yerr (SEM, a scalar, SD, or 95% CI) changes what the bars communicate.
plt.errorbar adds vertical whiskers to mean values, then compares how the choice of yerr (SEM, a scalar, SD, or 95% CI) changes what the bars communicate.
Section 8

8 Wrapping up Part I

Part II continues with labels and legends, several panels with subplots, and saving figures to a file.

Every matplotlib figure follows the same import, build, show skeleton, and the build step means choosing among four basic plots matched to your question, a line for trends and multiple series, a scatter for two variables, a bar with error bars for comparing groups under uncertainty, and a histogram for the distribution of one variable.
Every matplotlib figure follows the same import, build, show skeleton, and the build step means choosing among four basic plots matched to your question, a line for trends and multiple series, a scatter for two variables, a bar with error bars for comparing groups under uncertainty, and a histogram for the distribution of one variable.
Section 9

9 Check your understanding

You have reached the end of the module. Try the same questions again — your answers here, paired with your pre-test answers, are how we measure what the module taught you. Answer every question and confidence rating, then click Submit and see results to view your score.

Post-test

You write a Python script that ends with plt.plot(ages) and run it. The script finishes without errors but no figure window appears on screen. What is the most likely cause?

Post-test

You write fig, ax = plt.subplots() and want to draw a line on that panel using the object-oriented style. Which call is correct?

Post-test

You plot age (x) against BMI (y) for 200 unrelated patients and join the points with plt.plot. Why is the result misleading?

Post-test

You have one row per patient in a DataFrame and want to show the relationship between age and cholesterol. Which matplotlib call is the right one?

Post-test

You want to compare two patients' weight trajectories on the same axes. What is the simplest correct approach?

Post-test

You want to see the distribution of patient ages across your study. Which call produces the right plot?

Post-test

You have the mean BMI for each of three clinics (A, B, C) and want to compare them. Which call is the right one?

Post-test

You draw plt.hist(values, bins=3) on several hundred measurements and the distribution looks like a featureless block. What is the most sensible next step?

Post-confidence

I can decide whether a particular plot should be a line plot, a scatter plot, a bar plot, or a histogram, and explain why.

Not at all confident
Fully confident
Post-confidence

I can set up a matplotlib figure in either the pyplot or the object-oriented style, follow the import-build-show skeleton, and plot one or more series on the same axes.

Not at all confident
Fully confident
Section 10

10 Your results

Here is how your post-test answers compare with your pre-test answers. The pre/post pairing is the most reliable way to see what this module actually taught you.

Your score

Submit the post-test to see your results.

Muddiest point

What is the one thing from this module that is still unclear to you?

Rate this module

Overall, how would you rate this module?

How likely are you to recommend this module to a peer? (0 = not at all, 10 = extremely likely)