
Recall first from Grouping, missing data and time series
- groupby splits rows into groups, agg reduces each group to one summary row, and sort_values orders the summary
- NaN is a float sentinel that poisons arithmetic and is never equal to itself, so gaps are found with isna and repaired with dropna, fillna or ffill
- A sorted DatetimeIndex enables resample, which buckets samples onto a fixed grid, and rolling, which slides a window without changing the grid
Figures, axes and your first plot
4 min readIn the previous lesson you produced summary tables with groupby and resample. This lesson plots them with matplotlib and chooses between distribution, trend and composition charts while keeping the data-ink ratio high.
A table of boot times is honest but slow to read. When a reviewer asks "did the last kernel change make boot slower?", a chart answers in one glance where a column of forty numbers answers in two minutes. The catch is that a chart can also lie in one glance, so this lesson treats chart choice and labelling as engineering decisions, not decoration.
Install matplotlib into the same virtual environment you built for pandas (the project layout lesson covered venvs):
sudo apt install python3-venv # once, if python3 -m venv fails
python3 -m venv .venv
.venv/bin/pip install matplotlib pandas
The module you import is matplotlib.pyplot, conventionally aliased as plt. pyplot offers two styles. The stateful style, plt.plot(...) followed by plt.xlabel(...), acts on a hidden "current" figure and axes. The explicit style creates the objects first and calls methods on them. Use the explicit style in scripts: it stays readable when a figure grows to several plots, and it is what the matplotlib documentation recommends for anything beyond a quick interactive look.
The two objects you must keep straight are the the whole canvas, including all plots, titles and margins; it is the object you save to a file and the one plot area with its own x and y axis, ticks and labels; a figure can contain many axes. Note the spelling trap: Axes is one plot, not the plural of axis. plt.subplots() creates both in one call. Here is a complete first script; the numbers are illustrative sample values, so replace them with your own measurements:
import matplotlib.pyplot as plt
builds = list(range(1, 9))
boot_s = [12.4, 12.1, 11.8, 13.9, 12.0, 11.7, 11.6, 11.5]
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(builds, boot_s, marker="o", label="kernel 6.8")
ax.set_xlabel("Build number")
ax.set_ylabel("Boot time (s)")
ax.set_title("Boot time across eight builds")
ax.legend()
fig.savefig("boot_trend.png", dpi=150, bbox_inches="tight")
fig.savefig("boot_trend.svg", bbox_inches="tight")
Every line earns its place. figsize=(8, 4) sets the canvas size in inches. ax.plot draws a line chart; marker="o" marks the actual measurements so the reader can see there are eight samples, not a continuous recording. label= feeds the legend, and ax.legend() displays it. The set_xlabel, set_ylabel and set_title calls are not optional politeness: an axis without a unit is an unlabelled number. Finally fig.savefig writes the file. PNG is a raster image, good for chat and documents; dpi=150 gives crisp text (the default is 100). SVG is vector, so it stays sharp at any zoom, which makes it the right choice for web reports. bbox_inches="tight" trims the empty margin around the plot. pandas integrates directly: df["boot_s"].plot(ax=ax) draws a Series onto an existing Axes using matplotlib underneath.
matplotlib draws through a backend. The interactive backends need a display server, which a CI job, an SSH session and often WSL2 do not have. Select the non-interactive Agg backend, either with the environment variable MPLBACKEND=Agg (see environ(7) for how the process environment works) or with import matplotlib; matplotlib.use("Agg") before importing pyplot. With Agg, plt.show() does nothing useful, so always finish scripts with fig.savefig. Every script in this lesson runs headless.
Prepare the data: a list, a NumPy array or a pandas column from the previous lesson's groupby or resample.
Create the canvas:
fig, ax = plt.subplots(figsize=(w, h)).Draw:
ax.plot,ax.scatter,ax.hist,ax.boxplotorax.bar.Annotate: axis labels with units, a title that states the claim, a legend only if there is more than one series.
Save:
fig.savefig("name.png", dpi=150, bbox_inches="tight")and optionally an SVG copy.
Distribution, trend or composition: pick the chart first
4 min readA trend question asks how a value changes across an ordered axis: boot time per build, temperature per minute, latency across a resampled time series from the previous lesson. The chart is a line plot, ax.plot(x, y), because the connecting line asserts that neighbouring points belong to one sequence. That assertion is only valid when the x axis has a real order. If you connect unordered categories with a line, you invent a trend that does not exist.
A relationship question asks whether two variables move together: does latency rise when the CPU governor drops the frequency? The chart is a scatter plot, ax.scatter(x, y), with no connecting line, because each point is an independent pair. With hundreds of points, shrink them and add transparency so overlapping samples stay visible: ax.scatter(cpu_mhz, latency_ms, s=10, alpha=0.5).
A distribution question asks about the shape of one variable: are the 500 latency samples tightly grouped, or is there a long tail of rare slow responses that a mean would hide? Two charts serve this family. The histogram bins the values and counts each bin:
fig, ax = plt.subplots(figsize=(8, 4))
ax.hist(latency_ms, bins=30)
ax.set_xlabel("Latency (ms)")
ax.set_ylabel("Count")
ax.set_title("Latency distribution, 500 samples")
fig.savefig("latency_hist.png", dpi=150, bbox_inches="tight")
The bin count is a real decision, not a default to accept blindly: too few bins hide a second peak, too many turn the shape into noise. Try two or three values of bins and keep the one that shows a stable story. The y axis of a histogram is a count, so label it "Count", not the variable's unit.
The box plot compresses a distribution into five landmarks and excels at comparing groups side by side, for example latency under idle versus load:
fig, ax = plt.subplots(figsize=(6, 4))
ax.boxplot([idle_ms, loaded_ms])
ax.set_xticks([1, 2], labels=["idle", "loaded"])
ax.set_ylabel("Latency (ms)")
ax.set_title("Latency by system load")
fig.savefig("latency_box.png", dpi=150, bbox_inches="tight")
Box positions are numbered from 1, so set_xticks([1, 2], labels=...) names them. (Older tutorials pass labels= to boxplot; that keyword was renamed in matplotlib 3.9 and no longer exists in current releases, so name the ticks yourself as shown.) Read a matplotlib box plot precisely: the line inside the box is the median, the box spans the first to the third quartile, the whiskers reach the most extreme data points within 1.5 times the interquartile range of the box, and points beyond the whiskers are drawn individually as suspected outliers. It shows spread and skew compactly, but it hides bimodality: two peaks can produce the same box. When the shape itself matters, show the histogram too.
A composition question asks how a total splits into parts: how much of boot time is kernel versus userspace, per build. The chart is a stacked bar, built by drawing the second series with bottom= set to the first:
fig, ax = plt.subplots(figsize=(8, 4))
ax.bar(builds, kernel_s, label="kernel")
ax.bar(builds, userspace_s, bottom=kernel_s, label="userspace")
ax.set_xlabel("Build number")
ax.set_ylabel("Boot time (s)")
ax.legend()
fig.savefig("boot_composition.png", dpi=150, bbox_inches="tight")
Pie charts are the famous alternative for composition and usually the worse one: people compare lengths far more accurately than angles, so a stacked bar or a plain bar chart of the parts beats a pie in almost every engineering report. The next lesson builds proper boot stage charts on this pattern.
Visual clarity: data-ink and honest labels
4 min readTufte introduced the data-ink divided by total ink used in the graphic; Tufte argues most of a chart's ink should be data-ink in The Visual Display of Quantitative Information (1983). The practical editing pass is short. Remove the top and right frame lines (matplotlib calls the frame lines spines), because they enclose nothing. Lighten the grid or keep only horizontal grid lines, since the eye reads values against the y axis. Drop the legend when there is a single series: the title already names it. Never use 3-D effects, gradient fills or decorative backgrounds; Tufte calls the whole category visual elements that consume ink and attention without representing data, and every item on that list distorts readings as well as wasting space.
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.grid(axis="y", alpha=0.3)
Apply the same three lines to every axes in a script and your plots immediately look like measurement instruments instead of slide decorations. This matches the program's design rules: clarity first, no ornament.
Erasing ink has a limit, and honest labelling is on the other side of it. Three rules cover most failures. First, units on every axis: "Boot time (s)", never "time". Second, a title that states what is shown and on how much data: "Latency distribution, 500 samples" tells the reader the sample size, which changes how seriously to take a tail. Third, and most important, do not truncate a value axis on a bar chart. Bars encode value as length from zero, so starting the y axis at 90 makes a 5 percent difference look like a doubling. Keep ax.set_ylim(bottom=0) on bar charts. Line charts may zoom into a range because position, not length, carries the value, but say so in the axis labels so nobody misreads the scale.
A bar chart whose value axis starts above zero exaggerates every difference, even when the axis numbers are technically correct. Reviewers scan bar lengths, not tick labels. If the differences are genuinely small and worth showing, plot the differences themselves as a line or dot chart with a clearly labelled axis, instead of amputating the bars.
Finally, choose the output format for the destination. PNG is raster: it is made of pixels, dpi controls how many, and 150 to 200 is a good range for documents and review comments. SVG is vector: it stores the lines and text as shapes, stays sharp at any zoom, and is usually the smaller file for line art, so prefer it for web reports and anything a reader may zoom into. Saving both from the same Figure costs one extra line and covers both destinations. Because the figure is produced by a script from the data file, regenerating it after new measurements is one command, which is exactly the property the next lesson, "Percentiles, boot charts and reproducible reports", builds on: it adds percentile summaries to these charts and turns the scripts into reports you can rerun and trust.
Key takeaways
- plt.subplots() returns a Figure and an Axes: you draw on the Axes and save the Figure.
- Line charts answer trend questions, histograms and box plots answer distribution questions, stacked bars answer composition questions.
- On a headless machine select the Agg backend and use fig.savefig instead of plt.show().
- Tufte's data-ink ratio says remove ink that carries no data, and a bar chart's value axis must start at zero.
Reflect
- Explain to a colleague, in two sentences: create a Figure and Axes with plt.subplots and draw line, scatter, histogram and box plots
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Man pageenviron(7): the process environment, where MPLBACKEND is set
- DocumentationMatplotlib quick start: Figure, Axes and pyplot
- Documentationmatplotlib.pyplot.subplots: creating figures and axes
- DocumentationMatplotlib backends: Agg and headless rendering
Official documentation first. Links checked when the lesson was published.