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 add label="Cohort 1" to plt.plot but the legend does not appear in your figure. What else do you need?

Pre-test

You want to draw a horizontal reference line at y=7.0 across the whole plot to mark a clinical threshold. Which call adds it?

Pre-test

Your x-axis shows the numbers 0, 1, 2, but you want the ticks to read "Baseline", "Week 1", "Week 2" instead. Which call does this?

Pre-test

You write fig, axes = plt.subplots(1, 2) and try axes[0, 0].plot(...). Python raises IndexError: too many indices for array. What is the fix?

Pre-test

Inside a figure made with fig, axes = plt.subplots(1, 2), you want to give the LEFT panel its own title. Which approach is correct?

Pre-test

In a multi-panel figure, the subplot titles and axis labels overlap and collide with each other. Which single call fixes the spacing automatically?

Pre-test

You call plt.savefig("figure.png") after plt.show() in a script and the saved PNG file is blank. What should you do?

Pre-test

You are exporting a figure for a journal submission that must stay perfectly sharp at any zoom level. Which file format is the best choice?

Pre-confidence

I can build a one-panel matplotlib figure with axis labels, a title, and a legend, and save it as a PNG.

Not at all confident
Fully confident
Pre-confidence

I can build a two- or four-panel figure with plt.subplots, label every panel, and save the result as a 300-dpi PDF ready to drop into a paper or slide.

Not at all confident
Fully confident
Pre-confidence

I can customize a plot with a threshold line, custom axis limits, and named tick labels, and style its lines with colours, markers, and line styles.

Not at all confident
Fully confident
Section 2

2 Introduction

In Part I you drew line, scatter, bar and histogram plots. A correct plot can still be hard to read. A reader needs labels with units, a title and a legend. Plots that you want to compare should sit side by side in one figure. A finished figure should be saved to a file.

This lesson shows how to do each of these. It also covers threshold lines, axis limits, ticks and arrays shown as pictures.

Try every example in the Python Scratchpad on the right.

Section 3

3 Essential matplotlib customizations

A reader who has not seen your data needs to know what each axis measures, in which units, and which line is which.

Section 3.1

3.1 Labels, titles and legends

Add these four elements to every figure, even a quick one:

  • plt.xlabel() and plt.ylabel() name the axes. Include the units in parentheses, for example "Weight (kg)".
  • plt.title() writes a title above the plot.
  • plt.grid(True) draws a faint grid that makes the values easier to read.
  • plt.legend() draws a legend, which is a box that names each line. The names come from the label= arguments of your plt.plot() calls. A line with no label has no entry in the box.
Building a clear matplotlib figure by adding labels, title, grid, and legend one step at a time.
Building a clear matplotlib figure by adding labels, title, grid, and legend one step at a time.
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]
weight_kg = [82, 79, 75, 73]

plt.plot(months, weight_kg)
plt.xlabel("Months since baseline")
plt.ylabel("Weight (kg)")
plt.title("Patient weight during 12-month follow-up")
plt.grid(True)
plt.show()

Three more arguments change how a line looks. color takes a name such as steelblue or a hex code. linestyle takes - (solid), -- (dashed) or : (dotted). marker takes a symbol such as o (circle), s (square) or ^ (triangle).

Cycling through color, linestyle, and marker arguments in plt.plot to show how each one changes a line's appearance.
Cycling through color, linestyle, and marker arguments in plt.plot to show how each one changes a line's appearance.
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, color="steelblue", linestyle="-", marker="o", label="Patient A")
plt.plot(months, patient_b, color="darkorange", linestyle="--", marker="s", label="Patient B")
plt.xlabel("Months since baseline")
plt.ylabel("Weight (kg)")
plt.title("Two patients, twelve months")
plt.legend()
plt.show()
Section 3.2

3.2 Threshold, limits and custom ticks

A reader may need a clinical cutoff, a closer view of the data, or named categories. Three tools do this:

  • plt.axhline(y=...) draws a horizontal threshold line across the whole plot. plt.axvline(x=...) draws a vertical one. Both accept the color and linestyle arguments.
  • plt.xlim(lo, hi) and plt.ylim(lo, hi) set the lowest and highest value that each axis shows. These are the axis limits.
  • A tick is a mark on an axis. plt.xticks(positions, labels) replaces the numbers at the ticks with your own labels, such as "Before" and "After".
Marking thresholds with axhline and axvline, overriding the default zoom with xlim and ylim, and replacing numeric ticks with named categories using xticks.
Marking thresholds with axhline and axvline, overriding the default zoom with xlim and ylim, and replacing numeric ticks with named categories using xticks.

The next example draws a dashed red threshold line.

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]
hba1c = [7.2, 8.1, 6.5, 5.9]
plt.plot(months, hba1c, marker="o")
plt.axhline(y=7.0, color="red", linestyle="--", label="Threshold")
plt.xlabel("Month")
plt.ylabel("HbA1c (%)")
plt.legend()
plt.show()

Matplotlib fits the axis limits to the data and adds a small margin. With no arguments, plt.xlim() and plt.ylim() return the current limits. With two numbers, they set new limits.

import matplotlib.pyplot as plt

days = [1, 2, 3, 4, 5]
heart_rate = [72, 75, 71, 78, 74]

plt.plot(days, heart_rate)
print(plt.xlim())  # (0.8, 5.2)
print(plt.ylim())  # (70.65, 78.35)

plt.ylim(0, 100)
print(plt.ylim())  # (0.0, 100.0)
plt.show()

With the default limits, a change of 7 beats per minute fills almost the whole height of the plot. With limits of 0 and 100, the same change looks small. This is because it covers only 7 of the 100 units on the axis. So the limits decide how large a change looks.

The next example sets limits and tick labels.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import matplotlib.pyplot as plt

x = [0, 1, 2, 3, 4]
y = [10, 25, 30, 35, 40]
plt.plot(x, y, marker="o")
plt.xlim(-0.5, 4.5)
plt.ylim(0, 50)
plt.xticks([0, 1, 2, 3, 4], ["Baseline", "Week 1", "Week 2", "Week 4", "Week 12"])
plt.show()

Each tick needs one label. So the two lists must have the same length. Here, four positions have only three labels:

import matplotlib.pyplot as plt

plt.bar([0, 1, 2, 3], [12, 18, 25, 31])
plt.xticks([0, 1, 2, 3], ["Placebo", "Low", "Medium"])
# ValueError: The number of FixedLocator locations (4), usually from a call to set_ticks, does not match the number of ticklabels (3).

The message counts four locations and three labels. Add the missing label, or remove one position.

Section 4

4 Subplots and multiple figures

To compare datasets, put them in one figure. Readers can then compare the panels directly, without flipping between separate images.

fig, axes = plt.subplots(nrows, ncols) creates a grid of panels. It returns the whole figure and an array of the individual axes. In a grid with one row, axes[0] is the first panel from the left. axes[1] is the panel next to it.

Comparing datasets in one matplotlib figure with plt.subplots(1, 3), which returns a fig container and an axes array of panels.
Comparing datasets in one matplotlib figure with plt.subplots(1, 3), which returns a fig container and an axes array of panels.

With subplots, use the object-oriented style. Three points matter:

  • Call methods on a panel, not on plt. If ax is one panel, use ax.plot(), ax.set_title() and ax.set_xlabel(). A plt.something call changes only the most recently created panel.
  • figsize=(width, height) sets the whole figure size in inches. The default is 6.4 by 4.8. Use a wide figure for panels side by side, and a tall one for stacked panels.
  • plt.tight_layout() spaces the panels so that titles and labels do not overlap. Call it once, after the last panel.
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]

fig, axes = plt.subplots(1, 2, figsize=(10, 4))

axes[0].hist(ages, bins=8)
axes[0].set_title("Age distribution")
axes[0].set_xlabel("Age (years)")

axes[1].hist(bmi, bins=5)
axes[1].set_title("BMI distribution")
axes[1].set_xlabel("BMI")

plt.tight_layout()
plt.show()
Building a side-by-side matplotlib figure: set the canvas size with figsize, draw on each panel using its own axis object, then call tight_layout to fix the spacing.
Building a side-by-side matplotlib figure: set the canvas size with figsize, draw on each panel using its own axis object, then call tight_layout to fix the spacing.

An older way to build subplots is plt.subplot(nrows, ncols, index). It builds one panel at a time. The index starts at 1 and counts across each row, then down the grid. So plt.subplot(1, 2, 1) is the first panel. You will still see this style in other people’s code, including the PHM5005 course notebooks.

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.figure(figsize=(10, 4))

plt.subplot(1, 2, 1)
plt.hist(ages, bins=8)
plt.title("Age distribution")
plt.xlabel("Age (years)")

plt.subplot(1, 2, 2)
plt.hist(bmi, bins=5)
plt.title("BMI distribution")
plt.xlabel("BMI")

plt.tight_layout()
plt.show()

This code draws the same figure as the plt.subplots(1, 2) version above. In a bigger figure, each plt.something call after a plt.subplot(...) line changes the panel you selected last. No name refers to one panel, as axes[0] does. So use the object-oriented style for a figure you will keep adding to.

When a grid has several rows and columns, axes is a two-dimensional array. You pick one panel with two numbers, axes[row, col]. Both numbers start at 0.

import matplotlib.pyplot as plt

fig, axes = plt.subplots(1, 3)
print(axes.shape)  # (3,)
plt.show()

fig, axes = plt.subplots(2, 3)
print(axes.shape)  # (2, 3)
plt.show()

axes[1].plot([1, 2, 3])
# AttributeError: 'numpy.ndarray' object has no attribute 'plot'

With one row, axes.shape is (3,). So one number picks a panel. With two rows, axes.shape is (2, 3). So you need two numbers. Here axes[1] is the whole second row. It is an array of panels, and an array has no plot method. The next example fills a 2 by 2 grid.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import matplotlib.pyplot as plt

fig, axes = plt.subplots(2, 2, figsize=(8, 6))

axes[0, 0].plot([1, 2, 3], [1, 4, 9])
axes[0, 0].set_title("Top left")

axes[0, 1].scatter([1, 2, 3], [3, 1, 2])
axes[0, 1].set_title("Top right")

axes[1, 0].bar(["A", "B", "C"], [3, 5, 2])
axes[1, 0].set_title("Bottom left")

axes[1, 1].hist([1, 2, 2, 3, 3, 3, 4, 4, 5], bins=5)
axes[1, 1].set_title("Bottom right")

plt.tight_layout()
plt.show()
Each axes[row, col] expression picks one subplot in a 2D grid — the first index selects the row, the second selects the column.
Each axes[row, col] expression picks one subplot in a 2D grid — the first index selects the row, the second selects the column.

Limits have a second use: they make a comparison fair. By default, each panel fits its axes to its own data. So two histograms side by side can look alike even when their counts are very different.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import matplotlib.pyplot as plt

clinic_a = [92, 95, 88, 101, 97, 90, 99, 94, 96, 98,
            93, 100, 91, 95, 97, 89, 102, 96, 94, 98]
clinic_b = [90, 95, 100, 92, 97]

fig, axes = plt.subplots(1, 2, figsize=(10, 4))
axes[0].hist(clinic_a, bins=6)
axes[0].set_title("Clinic A (n=20)")
axes[0].set_xlabel("Glucose (mg/dL)")
axes[0].set_ylabel("Count")
axes[1].hist(clinic_b, bins=6)
axes[1].set_title("Clinic B (n=5)")
axes[1].set_xlabel("Glucose (mg/dL)")
axes[1].set_ylabel("Count")
plt.tight_layout()
plt.show()

Clinic B has only five readings. Its tallest bar holds 1 reading. The tallest bar of Clinic A holds 6 readings. Each panel fits its y-axis to its own data. So the tallest bar in each panel reaches almost the full height. The panels look alike, although the counts are very different.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import matplotlib.pyplot as plt

clinic_a = [92, 95, 88, 101, 97, 90, 99, 94, 96, 98,
            93, 100, 91, 95, 97, 89, 102, 96, 94, 98]
clinic_b = [90, 95, 100, 92, 97]

fig, axes = plt.subplots(1, 2, figsize=(10, 4))
axes[0].hist(clinic_a, bins=6)
axes[0].set_title("Clinic A (n=20)")
axes[0].set_xlabel("Glucose (mg/dL)")
axes[0].set_ylabel("Count")
axes[1].hist(clinic_b, bins=6)
axes[1].set_title("Clinic B (n=5)")
axes[1].set_xlabel("Glucose (mg/dL)")
axes[1].set_ylabel("Count")

top = max(axes[0].get_ylim()[1], axes[1].get_ylim()[1])
axes[0].set_ylim(0, top)
axes[1].set_ylim(0, top)

plt.tight_layout()
plt.show()

The call get_ylim() returns the lower and the upper limit. So get_ylim()[1] is the upper limit. The code gives the larger upper limit to both panels. Now the bars of Clinic B are much lower than the bars of Clinic A. This shows the real difference in counts.

Section 5

5 Saving figures

A figure that you only display is gone when you close it. The call plt.savefig("filename.ext") saves it to a file. The extension sets the format.

  • .png suits slides. The formats .pdf and .svg are vector formats. They store lines and text as shapes, not as pixels. So they stay sharp when you enlarge them. Avoid .jpg for plots. This is because its compression blurs lines and text.
  • dpi=300 saves 300 pixels for each inch of the figure. This is common for print.
  • bbox_inches="tight" trims the white border around the figure.
Matplotlib figures vanish when the popup window closes. To prevent this, save a clean image to disk.
Matplotlib figures vanish when the popup window closes. To prevent this, save a clean image to disk.

The next example saves a 6 by 4 inch figure at 100 dpi and 300 dpi. The function plt.imread reads each file back as an array of pixels. The shape lists the height first.

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6, 4))
ax.plot([0, 3, 6, 12], [82, 79, 75, 73])
fig.savefig("low.png", dpi=100)
fig.savefig("high.png", dpi=300)
plt.show()

print(plt.imread("low.png").shape[:2])  # (400, 600)
print(plt.imread("high.png").shape[:2])  # (1200, 1800)

At 6 by 4 inches, 100 dpi gives 600 by 400 pixels. At 300 dpi, the figure has three times as many pixels in each direction.

Two rules apply when you save:

  • Call plt.savefig() before plt.show(). This is because plt.show() displays the figure and closes it. A save after it writes an empty figure.
  • Close each figure that a loop makes. This is because Matplotlib keeps every figure open until you close it. A long loop then uses more and more memory. Add plt.close(fig) at the end of the loop body.
How a matplotlib loop creates one figure per iteration, line by line.
How a matplotlib loop creates one figure per iteration, line by line.
Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import matplotlib.pyplot as plt

patients = [
    ("P001", [82, 80, 78, 76]),
    ("P002", [91, 90, 88, 85]),
    ("P003", [70, 71, 70, 69]),
]

# One figure per patient -- save and close inside the loop.
for pid, weights in patients:
    fig, ax = plt.subplots()
    ax.plot([0, 3, 6, 12], weights, marker="o")
    ax.set_title(f"Weight trajectory -- {pid}")
    fig.savefig(f"{pid}_weight.png", dpi=300, bbox_inches="tight")
    plt.close(fig) # frees memory before the next iteration

Note: The saved files appear in the Files tab of the Python Scratchpad. You can download them to view the pictures.

Section 6

6 Showing an array as a picture

A digital image is a grid of numbers. The function plt.imshow(array) draws a two-dimensional array as a picture. Each cell becomes one pixel. The cell value decides the pixel shade. Here you build the array with NumPy. So there is no image file to load.

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

row = np.linspace(0, 1, 20)
image = np.zeros((20, 20)) + row
image[6:10, 6:10] = 1.0

plt.imshow(image, cmap="gray")
plt.colorbar(label="Pixel value")
plt.axis("off")
plt.show()

The variable row holds 20 values evenly spaced from 0 to 1. Adding it to a 20 by 20 block of zeros copies the values into every row. This makes a fade from black on the left to white on the right. The line image[6:10, 6:10] = 1.0 sets a 4 by 4 block of cells to 1.0. This draws a white square.

import numpy as np

row = np.linspace(0, 1, 20)
image = np.zeros((20, 20)) + row

print(image.shape)  # (20, 20)
print(image[0, 0])  # 0.0
print(image[0, 19])  # 1.0

In the picture, the top left cell holds 0.0 and is black. The top right cell holds 1.0 and is white.

Three settings style the picture:

  • cmap is short for colour map. A colour map turns each value into a shade. The setting cmap="gray" shows low values as black and high values as white. CT and MRI scans are usually shown this way.
  • plt.colorbar() adds a strip that shows which shade stands for which value.
  • plt.axis("off") hides the row and column numbers.
import numpy as np

row = np.linspace(0, 1, 20)
scan_a = np.zeros((20, 20)) + row
scan_b = np.zeros((20, 20)) + row * 0.4

print(scan_a.min(), scan_a.max())  # 0.0 1.0
print(scan_b.min(), scan_b.max())  # 0.0 0.4

By default, imshow stretches the colour scale to fit the data. With cmap="gray", the lowest value becomes black. The highest value becomes white. So Scan A uses a scale from 0.0 to 1.0. Scan B uses a scale from 0.0 to 0.4.

This suits one image. It misleads when you compare two images. This is because each image uses its own scale. So a darker scan can look as bright as a lighter one. The arguments vmin and vmax set the lowest and highest values of a shared scale.

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

row = np.linspace(0, 1, 20)
scan_a = np.zeros((20, 20)) + row
scan_b = np.zeros((20, 20)) + row * 0.4

fig, axes = plt.subplots(1, 2, figsize=(8, 4))
axes[0].imshow(scan_a, cmap="gray")
axes[0].set_title("Scan A")
axes[0].axis("off")
axes[1].imshow(scan_b, cmap="gray")
axes[1].set_title("Scan B")
axes[1].axis("off")
plt.show()

Scan B is darker than Scan A, but both panels look equally bright. This is because each panel uses its own scale.

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

row = np.linspace(0, 1, 20)
scan_a = np.zeros((20, 20)) + row
scan_b = np.zeros((20, 20)) + row * 0.4

fig, axes = plt.subplots(1, 2, figsize=(8, 4))
axes[0].imshow(scan_a, cmap="gray", vmin=0, vmax=1)
axes[0].set_title("Scan A")
axes[0].axis("off")
axes[1].imshow(scan_b, cmap="gray", vmin=0, vmax=1)
axes[1].set_title("Scan B")
axes[1].axis("off")
plt.show()

Both panels now use vmin=0 and vmax=1. Scan B never gets brighter than a dark grey. This is because its values stop at 0.4, which is 40% of the way up the scale.

The method .flatten() turns an array of pixel values into one row of numbers. Then plt.hist() can show how the values are spread. A tall bar at the far left means that most pixels are close to black. In a photograph, this can mean under-exposure. In a scan, it can be the black background around the body.

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

image = np.zeros((20, 20))
image[6:10, 6:10] = 0.9

plt.hist(image.flatten(), bins=20)
plt.xlabel("Pixel value")
plt.ylabel("Count")
plt.show()

Of the 400 cells, 384 hold 0. So the histogram has one tall bar at the far left. The 16 cells of the bright square hold 0.9. They make the small bar near 0.9.

Section 7

7 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 add label="Cohort 1" to plt.plot but the legend does not appear in your figure. What else do you need?

Post-test

You want to draw a horizontal reference line at y=7.0 across the whole plot to mark a clinical threshold. Which call adds it?

Post-test

Your x-axis shows the numbers 0, 1, 2, but you want the ticks to read "Baseline", "Week 1", "Week 2" instead. Which call does this?

Post-test

You write fig, axes = plt.subplots(1, 2) and try axes[0, 0].plot(...). Python raises IndexError: too many indices for array. What is the fix?

Post-test

Inside a figure made with fig, axes = plt.subplots(1, 2), you want to give the LEFT panel its own title. Which approach is correct?

Post-test

In a multi-panel figure, the subplot titles and axis labels overlap and collide with each other. Which single call fixes the spacing automatically?

Post-test

You call plt.savefig("figure.png") after plt.show() in a script and the saved PNG file is blank. What should you do?

Post-test

You are exporting a figure for a journal submission that must stay perfectly sharp at any zoom level. Which file format is the best choice?

Post-confidence

I can build a one-panel matplotlib figure with axis labels, a title, and a legend, and save it as a PNG.

Not at all confident
Fully confident
Post-confidence

I can build a two- or four-panel figure with plt.subplots, label every panel, and save the result as a 300-dpi PDF ready to drop into a paper or slide.

Not at all confident
Fully confident
Post-confidence

I can customize a plot with a threshold line, custom axis limits, and named tick labels, and style its lines with colours, markers, and line styles.

Not at all confident
Fully confident
Section 8

8 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)