Lesson 6 of 9
Module 2 · Figures that tell the truth
Journal figures combine several panels, labelled A, B, C. Building them in code, rather than pasting images together, keeps fonts, sizes and colours consistent and lets you rebuild the figure in seconds.
Before you start. This lesson uses tg and okabe from Choosing the right chart and bw from Comparisons and uncertainty. If you open a new notebook, or Colab has restarted, run this setup cell first.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
tg = pd.read_csv("toothgrowth.csv")
tg["supp"] = tg["supp"].map({"OJ": "Orange juice", "VC": "Ascorbic acid"})
okabe = {"Orange juice": "#E69F00", "Ascorbic acid": "#0072B2"}
bw = pd.read_csv("birthweight.csv")Small multiples: facets
Faceting repeats one plot for each group, on shared axes: facet_wrap(~ supp) in ggplot2, col="supp" in seaborn's figure-level functions (sns.catplot, sns.relplot).
A facet is one small panel in a grid of panels that all show the same kind of plot, each for a different subset of the data. The idea is often called small multiples. Because every panel uses the same axes, the reader's eye can move from one to the next and compare positions directly. With the tooth growth data, for example, faceting by supplement gives one panel for orange juice and one for ascorbic acid, each showing tooth length against dose.
In seaborn that takes one call. This draws the tooth growth strip plot as two facets, one per supplement:
g = sns.catplot(data=tg, x="dose", y="len", col="supp", kind="strip", height=3, aspect=0.9)
g.set_axis_labels("Dose (mg/day)", "Tooth length")
g.set_titles("{col_name}")col="supp" makes one column of panels per supplement, and kind="strip" chooses the strip plot. height is each panel's height in inches, and aspect its width as a multiple of the height. set_titles("{col_name}") titles each panel with just the group name, "Orange juice" or "Ascorbic acid", instead of seaborn's default "supp = Orange juice".
Facets and colour are two ways to split the same data, and the choice decides which comparison is easiest. Within one panel, the reader compares positions side by side; across panels, they have to move their eyes and remember. So put the comparison that matters most inside each panel, and use facets for the rest. In Choosing the right chart the two supplements shared one panel, because the question was how they compare at each dose. Faceting by supplement instead makes the dose pattern within each supplement clearer, and the supplement comparison harder. A common pitfall is to set sharey=False so that each facet fills its own panel. The panels then look more alike than the data are, because each has been stretched to fit, as Honest axes and scales showed.
Seaborn has two kinds of plotting function, and the difference matters here. Figure-level functions, such as sns.catplot, sns.relplot and sns.lmplot, build a whole new figure, including any facets, and cannot be placed inside a figure you have already made. Axes-level functions, such as sns.stripplot, sns.scatterplot and sns.regplot, draw into one plotting area that you hand them with ax=. Faceting suits one kind of plot repeated; when the panels are different kinds of plot, as in a typical journal figure, you build the grid yourself and use axes-level functions, as below.
The term "small multiples" was popularised by Edward Tufte in his books on information design, starting with The Visual Display of Quantitative Information (Graphics Press, 1983). Rougier, Droettboom & Bourne (2014), "Ten simple rules for better figures", PLOS Computational Biology 10(9): e1003833, written partly by a matplotlib developer, covers several points in this lesson: adapt the figure to where it will appear, do not trust the defaults, and use colour with care. The birth weight data come from Hosmer & Lemeshow's textbook Applied Logistic Regression (Wiley, 1989) and are distributed in R's MASS package as birthwt. Cite the original source of a teaching dataset, not only the package that supplied it.
Different plots side by side
The code combines two figures you have already met: the tooth growth strip plot from Choosing the right chart and the birth weight scatter plot from Comparisons and uncertainty, where bw holds 189 births with the mother's weight (lwt, in pounds), the baby's birth weight (bwt, in grams) and whether the mother smoked (smoke).
fig, axes = plt.subplots(1, 2, figsize=(180 / 25.4, 85 / 25.4)) # mm to inches
sns.stripplot(data=tg, x="dose", y="len", hue="supp", palette=okabe, dodge=True, alpha=0.7, ax=axes[0])
sns.regplot(data=bw[bw["smoke"] == "non-smoker"], x="lwt", y="bwt", color="#0072B2",
scatter_kws={"alpha": 0.6, "s": 12}, ax=axes[1], label="non-smoker")
sns.regplot(data=bw[bw["smoke"] == "smoker"], x="lwt", y="bwt", color="#E69F00",
scatter_kws={"alpha": 0.6, "s": 12}, ax=axes[1], label="smoker")
axes[0].set(xlabel="Dose (mg/day)", ylabel="Tooth length")
axes[1].set(xlabel="Mother's weight (lb)", ylabel="Birth weight (g)")
for ax, letter in zip(axes, "AB"):
ax.text(-0.15, 1.05, letter, transform=ax.transAxes, fontsize=13, fontweight="bold")
ax.legend(frameon=False, fontsize=8)
sns.despine()
plt.tight_layout()
fig.savefig("figure1.png", dpi=300)What this does
- The grid.
plt.subplots(1, 2, figsize=...)makes one figure with two plotting areas side by side. In matplotlib a plotting area is called an Axes (one panel, with its own x- and y-axis), and axes is the pair of them. Matplotlib measures figure size in inches, so the code divides millimetres by 25.4, the number of millimetres in an inch: the figure will be 180 mm wide and 85 mm tall. - Panel A.
sns.stripplotdraws every animal as a dot: dose on the x-axis, tooth length on the y-axis, coloured by supplement with the okabe colours from Choosing the right chart.dodge=Trueplaces the two supplements side by side within each dose instead of on top of each other, andalpha=0.7makes the dots slightly see-through so overlapping animals show.ax=axes[0]sends it to the left panel. - Panel B.
sns.regplotis called twice, once for non-smokers and once for smokers, each time on the rows selected withbw["smoke"] == .... Each call draws the points, a fitted straight line and a shaded band (by default, the 95% confidence interval for the line).scatter_kwspasses settings to the points only:alphafor transparency andsfor marker size. Both calls useax=axes[1], so they share the right panel, andlabelgives each a name for the legend. The colours are the same blue and orange as in panel A, here standing for non-smokers and smokers. - Labels.
axes[0].set(...)andaxes[1].set(...)give each panel its axis labels, with units. - Letters and legends.
zip(axes, "AB")pairs the first panel with "A" and the second with "B". For each pair,ax.text(-0.15, 1.05, letter, transform=ax.transAxes, ...)writes the letter in bold.transform=ax.transAxesmeans the two numbers are fractions of that panel, not data values: 0 is the panel's left or bottom edge and 1 its right or top edge. So −0.15 is a little to the left of the panel and 1.05 a little above it, the usual place for a panel letter.ax.legend(frameon=False, fontsize=8)draws each panel's legend without a box. - Finishing.
sns.despine()removes the top and right border lines,plt.tight_layout()spaces the panels so nothing overlaps, andfig.savefig("figure1.png", dpi=300)writes the file at 300 dots per inch: about 2,126 pixels across for 7.09 inches.
Because the letters are placed in panel fractions, not data units, the same line works for any panel, whatever its data range. That is what lets one short loop label every panel.
Building the whole figure in one script, rather than saving two plots and arranging them in a drawing program, pays off later. When a reviewer asks for one extra sample or a corrected label, you change one line and run the script again, and both panels update with the same fonts, sizes and colours. A figure assembled by hand has to be rebuilt by hand, and that is where mismatched panels and out-of-date versions creep in.
Reading the finished figure
Panel A shows each guinea pig as a dot, grouped by dose and split by supplement, so a reader sees both the spread within each group and how the groups compare. Panel B shows each birth as a dot, with a fitted line and confidence band for smokers and non-smokers. The two panels answer different questions, so they use different kinds of plot, but they share one font, one size of text, one style of panel letter and one pair of colours. That shared style is what makes the two read as one figure instead of two pictures placed side by side.
When you check a multi-panel figure of your own, read it as a stranger would. Does each panel have its letter, its axis labels and its units? Can the reader tell which legend belongs to which panel? Are the panels that will be compared drawn on the same scale? A panel that fails any of these is the one readers will misread, however good the others are.
The colours deserve a closer look. Blue and orange mean different groups in the two panels (supplements in A, smoking status in B), and each panel has its own legend saying so. When panels show the same groups, the rule is stricter: a group must keep its colour in every panel, which is why Choosing the right chart stored the colours in a named dictionary, okabe, instead of retyping them.
Worked example · figure sizes
180 mm ÷ 25.4 = 7.09 inches for matplotlib's
figsizedesign at the final size, so 11-point text stays 11 points when printed
Step by step. There are 25.4 mm in an inch, so 180 mm ÷ 25.4 = 7.087 inches, which rounds to 7.09. That number goes straight into figsize. Text size is measured in points, and one point is 1/72 of an inch, so an 11-point label is a fixed physical size on the page.
What the answer means. Suppose instead you drew the figure 14 inches wide on screen and the journal shrank it to 7.09 inches to fit the page. Everything would be scaled by 7.09 ÷ 14 = 0.51, and your 11-point labels would print at about 5.6 points, too small to read comfortably. Designing at the final size avoids that surprise: what you see on screen is what will print.
Go deeper: panels of different sizes with subplot_mosaic
plt.subplots gives panels of equal size. When one panel needs more room, such as a heatmap next to two small plots, plt.subplot_mosaic lets you sketch the layout as text. Each letter is a panel, and repeating a letter makes that panel span more space: fig, axd = plt.subplot_mosaic("ABCC", figsize=(180 / 25.4, 60 / 25.4)) makes one row in which panel C is twice as wide as A or B.
The result, axd, is a dictionary of axes keyed by their letters, so you draw with ax=axd["C"] and can loop over axd.items() to write each panel letter. A list of lists describes several rows: [["A", "C"], ["B", "C"]] puts A above B on the left, with C filling the full height on the right. Adding layout="constrained" to the call spaces the panels automatically, in place of plt.tight_layout().
Key point
Use the same colours for the same groups in every panel, align axes that readers will compare, and keep one legend where several panels share it.
A second example. In an omics figure, panel A might be a PCA plot with control samples in blue and treated samples in orange, and panel B a heatmap with a colour bar above the columns. If the colour bar uses orange for control, readers will misread one of the two panels, even though each is correct on its own. Choose the colours for each group once, at the top of the script, and use them everywhere.
Further reading · Module 2Weissgerber et al. 2015: why bar charts hide the data. · All reading for this course
Check your understanding
1. What does ax.text(-0.15, 1.05, "A", transform=ax.transAxes) do?
2. Why build multi-panel figures in code rather than in a drawing program?
3. A figure 85 mm wide is what in inches?
Up next
Lesson 7
Omics figures