TExcelTAD
Home › Matplotlib › Matplotlib Exercises

Matplotlib Exercises

Time to practise! Each exercise has a starter playground that already runs: it draws a rough version of the chart and prints a check line. Complete the TODO parts, press ▶ Run, and compare both the picture and the printed line with the "Expected" description. Solutions are hidden below each exercise. Try for a few minutes before peeking.

# Exercise Topics
1 Labelled line chart plot, title, labels, markers
2 Two series with a legend colours, line styles, legend
3 Sorted horizontal bars barh, sorting, bar labels
4 Histogram with a mean line hist, bins, axvline
5 A 2 × 2 dashboard subplots, sharex, tight layout
6 Colour-coded scatter scatter, colormap, colorbar
7 Annotate the maximum annotate, argmax
8 Save to memory savefig, BytesIO, dpi

1. Labelled line chart

Plot the number of books read per month. Add circle markers, the title "Books read in 2024", the x label "Month" and the y label "Books".

Expected output: title='Books read in 2024' xlabel='Month' ylabel='Books' marker=o

python · try it yourself
import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
books = [2, 3, 1, 4, 3, 5]

fig, ax = plt.subplots()
ax.plot(months, books)          # TODO: add circle markers
# TODO: title and axis labels
plt.show()

line = ax.lines[0]
print(f"title={ax.get_title()!r} xlabel={ax.get_xlabel()!r} ylabel={ax.get_ylabel()!r} marker={line.get_marker()}")
title='' xlabel='' ylabel='' marker=None
Show solution
python
import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
books = [2, 3, 1, 4, 3, 5]

fig, ax = plt.subplots()
ax.plot(months, books, marker="o")
ax.set(title="Books read in 2024", xlabel="Month", ylabel="Books")
plt.show()

line = ax.lines[0]
print(f"title={ax.get_title()!r} xlabel={ax.get_xlabel()!r} ylabel={ax.get_ylabel()!r} marker={line.get_marker()}")

2. Two series with a legend

Plot sin(x) as a solid blue line and cos(x) as a dashed red line, label them "sin" and "cos", and show a legend in the lower left corner.

Expected output: sin - b and cos -- r on two lines, then legend: ['sin', 'cos']

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 100)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x))           # TODO: colour, style, label
ax.plot(x, np.cos(x))           # TODO: colour, style, label
# TODO: legend in the lower left
plt.show()

for line in ax.lines:
    print(line.get_label(), line.get_linestyle(), line.get_color())
legend = ax.get_legend()
print("legend:", [t.get_text() for t in legend.get_texts()] if legend else None)
_child0 - #1f77b4
_child1 - #ff7f0e
legend: None
Show solution
python
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 100)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x), "b-", label="sin")
ax.plot(x, np.cos(x), "r--", label="cos")
ax.legend(loc="lower left")
plt.show()

The format strings "b-" and "r--" set colour and line style at once; color="b", linestyle="-" works too. Note the check prints sin - b with the short colour name you used.

3. Sorted horizontal bars

Show the population of these cities as horizontal bars, largest at the top, with the value written at the end of each bar.

Expected output: order (bottom to top): ['Lyon', 'Milan', 'Madrid', 'Berlin'] and labels: 4

python · try it yourself
import matplotlib.pyplot as plt

population = {"Berlin": 3.9, "Madrid": 3.4, "Lyon": 0.5, "Milan": 1.4}   # millions

fig, ax = plt.subplots()
names = list(population.keys())          # TODO: sort by value
values = list(population.values())
bars = ax.barh(names, values)
# TODO: add value labels with bar_label
plt.show()

print("order (bottom to top):", [t.get_text() for t in ax.get_yticklabels()])
print("labels:", len(ax.texts))
order (bottom to top): ['Berlin', 'Madrid', 'Lyon', 'Milan']
labels: 0
Show solution
python
import matplotlib.pyplot as plt

population = {"Berlin": 3.9, "Madrid": 3.4, "Lyon": 0.5, "Milan": 1.4}

ranked = sorted(population.items(), key=lambda kv: kv[1])
names = [name for name, _ in ranked]
values = [value for _, value in ranked]

fig, ax = plt.subplots()
bars = ax.barh(names, values, color="C0")
ax.bar_label(bars, fmt="%.1f M", padding=3)
ax.set_xlim(0, 4.6)                      # room for the labels
ax.set_xlabel("Population (millions)")
plt.show()

barh draws the first category at the bottom, so ascending order puts the largest bar on top.

4. Histogram with a mean line

Draw a histogram of the 1000 exam scores with 20 bins and white bar edges, then add a dashed vertical line at the mean.

Expected output: bins: 20 and mean line at 70.0

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(99)
scores = np.clip(rng.normal(70, 12, 1000), 0, 100)

fig, ax = plt.subplots()
counts, edges, _ = ax.hist(scores)      # TODO: 20 bins, white edges
# TODO: dashed vertical line at the mean
plt.show()

print("bins:", len(counts))
vlines = [l for l in ax.lines if len(set(l.get_xdata())) == 1]
print(f"mean line at {vlines[0].get_xdata()[0]:.1f}" if vlines else "no mean line yet")
bins: 10
no mean line yet
Show solution
python
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(99)
scores = np.clip(rng.normal(70, 12, 1000), 0, 100)

fig, ax = plt.subplots()
counts, edges, _ = ax.hist(scores, bins=20, edgecolor="white")
ax.axvline(scores.mean(), color="k", linestyle="--", label=f"mean {scores.mean():.1f}")
ax.legend()
plt.show()

5. A 2 × 2 dashboard

Create a 2 × 2 grid of subplots (size 8 × 6, constrained layout) showing: a line (top left), bars (top right), a scatter (bottom left) and a pie (bottom right) of the given data. Give each panel a title.

Expected output: panels: 4 and titles: ['Line', 'Bars', 'Scatter', 'Pie']

python · try it yourself
import matplotlib.pyplot as plt

values = [4, 7, 3, 8, 5]
labels = ["A", "B", "C", "D", "E"]

fig, ax = plt.subplots()           # TODO: 2 x 2 grid, figsize, layout
ax.plot(values)
ax.set_title("Line")
# TODO: the other three panels
plt.show()

print("panels:", len(fig.axes))
print("titles:", [a.get_title() for a in fig.axes])
panels: 1
titles: ['Line']
Show solution
python
import matplotlib.pyplot as plt

values = [4, 7, 3, 8, 5]
labels = ["A", "B", "C", "D", "E"]

fig, axes = plt.subplots(2, 2, figsize=(8, 6), layout="constrained")
axes[0, 0].plot(labels, values, marker="o")
axes[0, 0].set_title("Line")
axes[0, 1].bar(labels, values, color="C1")
axes[0, 1].set_title("Bars")
axes[1, 0].scatter(range(5), values, s=[v * 20 for v in values], color="C2")
axes[1, 0].set_title("Scatter")
axes[1, 1].pie(values, labels=labels)
axes[1, 1].set_title("Pie")
plt.show()

print("panels:", len(fig.axes))
print("titles:", [a.get_title() for a in fig.axes])

6. Colour-coded scatter

Scatter x against y, colour each point by its distance from the origin using the "plasma" colormap, and add a colorbar labelled "distance".

Expected output: colormap: plasma and colorbar label: distance

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(5)
x = rng.normal(0, 1, 300)
y = rng.normal(0, 1, 300)
distance = np.sqrt(x ** 2 + y ** 2)

fig, ax = plt.subplots()
sc = ax.scatter(x, y)                  # TODO: colour by distance with plasma
# TODO: colorbar with a label
ax.set_aspect("equal")
plt.show()

print("colormap:", sc.get_cmap().name)
print("colorbar label:", fig.axes[1].get_ylabel() if len(fig.axes) > 1 else None)
colormap: viridis
colorbar label: None
Show solution
python
fig, ax = plt.subplots()
sc = ax.scatter(x, y, c=distance, cmap="plasma", s=15)
fig.colorbar(sc, ax=ax, label="distance")
ax.set_aspect("equal")
plt.show()

The colorbar lives in its own (second) Axes; its label is that Axes' y label.

7. Annotate the maximum

Find the hottest day and annotate it with an arrow and the text "Hottest: 34 °C", placed above and to the left of the point.

Expected output: annotations: ['Hottest: 34 °C'] and points at: (6, 34)

python · try it yourself
import matplotlib.pyplot as plt

day = list(range(1, 11))
temp = [24, 26, 25, 29, 31, 34, 30, 27, 26, 28]

fig, ax = plt.subplots()
ax.plot(day, temp, marker="o")
ax.set_ylim(20, 40)
# TODO: find the maximum and annotate it
plt.show()

notes = [t for t in ax.texts]
print("annotations:", [t.get_text() for t in notes])
if notes:
    print("points at:", tuple(int(v) for v in notes[0].xy))
annotations: []
Show solution
python
i = temp.index(max(temp))
ax.annotate(f"Hottest: {temp[i]} °C", xy=(day[i], temp[i]),
            xytext=(day[i] - 4, temp[i] + 4),
            arrowprops=dict(arrowstyle="->"))

8. Save to memory

Save the figure into an io.BytesIO buffer as a PNG at 150 dpi with bbox_inches="tight", then print the buffer size and the image width read from the PNG header.

Expected output: saved: True and width: 522 px: a bit below 600 px (4 inches × 150 dpi), because the empty margins are cropped.

python · try it yourself
import io
import struct
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(4, 3))
ax.bar(["x", "y", "z"], [3, 5, 2])

buffer = io.BytesIO()
# TODO: save the figure into buffer
data = buffer.getvalue()

print("saved:", data[:4] == b"\x89PNG")
if data:
    width, height = struct.unpack(">II", data[16:24])
    print("width:", width, "px")
plt.close(fig)
saved: False
Show solution
python
fig.savefig(buffer, format="png", dpi=150, bbox_inches="tight")

Without bbox_inches="tight" the width would be exactly 4 × 150 = 600 px.

Test yourself

Which call puts the largest bar at the top of a horizontal bar chart?

  1. Sort the data in ascending order before barh()
  2. Sort the data in descending order before barh()
  3. ax.invert_xaxis()
  4. barh(..., top=True)

After fig.colorbar(sc, ax=ax), how many Axes does the figure contain?

  1. 1
  2. 2
  3. 3
  4. 0