LSMA

LONDON SCHOOL OF MULTIOMICS & AI

Free course

Free course

0 of 35 lessons

Lesson 6 of 9

Module 2 · Figures that tell the truth

Multi-panel figures

Multi-panel figures

Multi-panel figures

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.

⏱ 10 min readModule 2 · Figures that tell the truthFree
Lesson at a glance4 steps · about 10 min
  1. Small multiples: facets
  2. Different plots side by side
  3. What this does
  4. Reading the finished figure

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.

Python · setup
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")
Files for this lessonSave each file under the name shown here, next to your notebook, or upload it to Colab (folder icon › Upload). Your browser may give the download a different name; rename it before you run the code.
toothgrowth.csvTooth growth in 60 guinea pigs given vitamin C birthweight.csv189 births: birth weight, mother's weight and age, smoking

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:

Python
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).

Python
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.stripplot draws 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=True places the two supplements side by side within each dose instead of on top of each other, and alpha=0.7 makes the dots slightly see-through so overlapping animals show. ax=axes[0] sends it to the left panel.
  • Panel B. sns.regplot is called twice, once for non-smokers and once for smokers, each time on the rows selected with bw["smoke"] == .... Each call draws the points, a fitted straight line and a shaded band (by default, the 95% confidence interval for the line). scatter_kws passes settings to the points only: alpha for transparency and s for marker size. Both calls use ax=axes[1], so they share the right panel, and label gives 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(...) and axes[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.transAxes means 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, and fig.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.

Multi-panel figures · LSMA free course A figure 180 millimetres wide and 85 millimetres tall holds two panels, axes zero and axes one. Each panel's bottom-left corner is (0, 0) and top-right corner is (1, 1) in panel fractions; the panel letter sits at (minus 0.15, 1.05), a little above and to the left of the panel. ONE FIGURE (FIG) HOLDING TWO AXES fig A B (−0.15, 1.05) (0, 0) (1, 1) axes[0] axes[1] 180 mm wide = 7.09 inches in figsize 85 mm
Each panel has its own coordinate system in fractions, from (0, 0) at its bottom-left corner to (1, 1) at its top-right. The letter at (−0.15, 1.05) therefore lands a little outside the top-left corner of every panel. Schematic, not to scale.
Panel A: tooth length by dose and vitamin C source. Panel B: birth weight against mother's weight for smokers and non-smokers, each with a fitted line and confidence band.
The finished two-panel figure at 180 mm wide, a full page width in most journals. This image was drawn with R's ggplot2; the Python code above gives the same two panels in matplotlib's style.

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

single column ≈ 85–90 mm · full width ≈ 170–180 mm (check the journal's guide)
180 mm ÷ 25.4 = 7.09 inches for matplotlib's figsize
design 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

Ask BioTutor

Create a free website with Framer, the website builder loved by startups, designers and agencies.