LSMA

LONDON SCHOOL OF MULTIOMICS & AI

Free course

Free course

0 of 35 lessons

Lesson 1 of 9

Module 2 · Figures that tell the truth

Choosing the right chart

Choosing the right chart

Choosing the right chart

A figure answers one question. Decide the question first, and the chart usually chooses itself.

⏱ 12 min readModule 2 · Figures that tell the truthFree
Lesson at a glance5 steps · about 12 min
  1. How to read the table below
  2. The tooth growth data
  3. What this does
  4. Reading the output
  5. Reading the figure
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

In Python basics you loaded, cleaned and combined tables with pandas, drew your first figures with matplotlib and seaborn, and put them into a sequence and sample report. Those figures ran without errors, but a figure that runs is not yet a figure that is honest and easy to read. This module is about the choices behind a figure: which chart answers the question, how to show spread and uncertainty, which colours, axes and panels to use, and how to export the result. It starts with the first of those choices, the type of chart.

How to read the table below

Start from the left column: find the question your figure has to answer. The middle column lists charts that answer it well, and the right column a common choice that answers it badly. Most bad figures are not badly drawn; they are good drawings of the wrong chart for the question.

Starting from the question matters because the same data can answer several questions, and each needs a different chart. Take the expression of one gene measured in tumour and normal tissue from 40 patients. "Is expression higher in tumours?" is a comparison of groups, so points per group with a summary on top. "Does expression in each tumour track the patient's age?" is a relation between two measures, so a scatter plot. Same numbers, two figures. A common pitfall is to start from whatever chart the software draws by default and then look for a question it answers.

The questionGood choicesAvoid
How are values spread?Histogram, density, box with points, violinA single bar of the mean
How do groups compare?Points with mean and confidence intervalBars with an error bar, for continuous data
How do two measures relate?Scatter plot, with a fitted line if usefulTwo lines on two different axes
How does something change over time?Line plot, with points for few timesPie charts at each time
What are the parts of a whole?Stacked bar, or simply a table3D pie charts
Patterns across many genes and samples?Clustered heatmap, PCADozens of separate bar charts

Some terms in the table, briefly:

  • A density plot is a smoothed histogram: a continuous curve showing where values are common and where they are rare.
  • A confidence interval is a range around an estimate, such as a mean, that shows how precisely it is known. Comparisons and uncertainty computes one.
  • Continuous data are measurements that can take any value in a range, such as a length or an expression level, as opposed to counts or categories.
  • PCA, principal component analysis, summarises many measurements, for example thousands of genes, into a few new axes that capture most of the variation, so that samples can be drawn as points on a flat plot.

Two of the "avoid" entries are worth a reason each. Two lines on two different y axes can be made to look related or unrelated by stretching either scale, so the picture depends on a choice the reader cannot see. 3D pie charts tilt the slices, so slices at the front look larger than slices of the same size at the back.

The other entries have reasons too. A bar suggests a quantity that builds up from zero, which suits counts but not a measurement such as a length, and it shows one number per group while hiding how the values behind it are spread. The error bar on top may be a standard deviation, a standard error or a confidence interval, and figures often do not say which. Separate pies at each time point force the reader to compare angles across circles, which people do poorly; a line through the same values puts them on one scale. Dozens of separate bar charts make the reader hold each panel in memory to compare it with the next, while a heatmap shows the whole pattern at once.

When your question is not in the table, ask what the reader must compare, and put those things next to each other on a common scale. If the comparison is treated against untreated at each of four time points, the treated and untreated values for one time should sit side by side, not in separate panels.

The tooth growth data

Sixty guinea pigs received vitamin C at 0.5, 1 or 2 mg a day, as orange juice or as pure ascorbic acid, and the length of their tooth-forming cells was measured. Ten animals per group: few enough to show every one.

This is a classic teaching dataset with two factors: the supplement, two types, and the dose, three levels. Crossing them gives 2 × 3 = 6 groups, and the question is how tooth length depends on both. That is a "how do groups compare?" question, so the table points to points with a summary on top.

A factor is a variable that sorts observations into groups, and its levels are the groups it can take. Dose is a number, but here it works as a factor with three levels, because only three doses were given. This has a visible consequence. seaborn's stripplot and pointplot treat the x values as categories by default and space them evenly, so the step from 1 to 2 mg looks the same as the step from 0.5 to 1 mg. That is fine for comparing groups. If the spacing of the doses matters to your question, seaborn's native_scale=True option places them at their real values instead.

The dataset suits this module because it is small, its design is balanced, with the same number of animals in every group, and its answer is well known. That lets you concentrate on how the figure shows the answer rather than on what the answer is.

Choosing the right chart · LSMA free course A grid of six groups: two supplements, orange juice and ascorbic acid, crossed with three doses, 0.5, 1 and 2 mg a day. Each group holds ten animals, drawn as ten dots, with the group mean tooth length underneath. 1 · 60 ANIMALS IN SIX GROUPS OF TEN 0.5 mg/day 1 mg/day 2 mg/day Orange juice mean 13.2 mean 22.7 mean 26.1 Ascorbic acid mean 8.0 mean 16.8 mean 26.1 2 supplements × 3 doses × 10 animals = 60
Every combination of supplement and dose was given to ten different animals. The means under each group are the ones printed by the code below. Schematic, not to scale.
Python
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"}

print(tg.groupby(["supp", "dose"])["len"].agg(["count", "mean"]).round(1))

fig, ax = plt.subplots(figsize=(5, 3.5))
sns.stripplot(data=tg, x="dose", y="len", hue="supp", palette=okabe, dodge=True, alpha=0.7, ax=ax)
sns.pointplot(data=tg, x="dose", y="len", hue="supp", palette=okabe, dodge=0.4,
              linestyle="none", errorbar=None, marker="_", markersize=20, ax=ax, legend=False)
ax.set_xlabel("Vitamin C dose (mg/day)"); ax.set_ylabel("Tooth length")
ax.legend(title=None, frameon=False)
sns.despine()
fig.savefig("tooth_growth.png", dpi=300, bbox_inches="tight")
count mean supp dose Ascorbic acid 0.5 10 8.0 1.0 10 16.8 2.0 10 26.1 Orange juice 0.5 10 13.2 1.0 10 22.7 2.0 10 26.1

What this does

  • Loading and labelling. The file has three columns: len, supp and dose. .map({…}) replaces each short code with a readable name, OJ with "Orange juice" and VC (vitamin C) with "Ascorbic acid", so the legend explains itself.
  • Colours. okabe fixes one colour per group, orange and blue from the Okabe–Ito palette (Colour that works for everyone).
  • The summary. groupby(["supp", "dose"]) splits the table into the six groups; ["len"] picks the measurement; .agg(["count", "mean"]) computes both for each group; .round(1) rounds to one decimal place.
  • The points. sns.stripplot draws one dot per animal, with dose along x. dodge=True places the two supplements side by side at each dose instead of on top of each other, and alpha=0.7 makes the dots slightly see-through, so overlapping dots show as darker.
  • The means. sns.pointplot draws each group's mean, by default. marker="_" with markersize=20 makes it a short horizontal line; linestyle="none" stops it joining the means with lines; errorbar=None leaves out error bars; dodge=0.4 shifts the marks sideways so they sit over their own dots; and legend=False stops a second, duplicate legend.
  • Finishing. The axis labels say what was measured and in which units. ax.legend(title=None, frameon=False) removes the legend's title and box. sns.despine() removes the top and right border lines, which carry no information.

Two choices in this code are worth copying. First, the colours are fixed in a dictionary rather than left to seaborn. A dictionary maps each group name to one colour, so "Orange juice" is orange in this figure and in every later one, whatever order the groups appear in. Second, the two layers are drawn on the same axes, ax, one after the other: the points first, then the means on top. Later calls draw over earlier ones, so the order decides what stays visible. If the mean lines do not sit over their own dots on your computer, the usual cause is a mismatch between the two dodge settings; adjust dodge in pointplot until they line up. The dpi=300 and bbox_inches="tight" settings in savefig are explained in Publication-ready export, later in this module.

Reading the output

The table is indexed by two levels, supplement then dose, listed in sorted order; a blank under supp means "same as the line above". count is 10 in every group, confirming the design. The mean column rises with dose for both supplements, and the dose is printed as 0.5, 1.0 and 2.0 because the column holds decimal numbers.

Strip plot of tooth length by vitamin C dose, every animal shown, with a short line at each group's mean. Length rises with dose; orange juice is higher than ascorbic acid at 0.5 and 1 mg, and equal at 2 mg.
Drawn by the Python code above.

Reading the figure

Each dot is one animal, and each short line is its group's mean. Because every animal is visible, you can judge more than the means: how much animals within a group differ, how far the groups overlap, and whether any single animal sits far from the rest. A bar chart of the same six means would show none of that.

Here, for example, the two clouds of points at 2 mg sit on top of each other, which matches the equal means, while at 0.5 mg the orange juice dots sit mostly above the ascorbic acid dots. On real omics data the same habit pays off even more. An experiment with three replicates per condition should show all three, because a reader who sees that one replicate sits far from the other two will read the result very differently from one who sees only a mean.

Worked example · what the figure says in one sentence

tooth length rises with dose for both sources
at 0.5 and 1 mg orange juice is ahead by about 5–6 units (13.2 vs 8.0; 22.7 vs 16.8)
at 2 mg the two are the same (26.1 and 26.1)

If you cannot say what a figure shows in one sentence, it is probably trying to answer more than one question.

Step by step. Read the means from the table. At 0.5 mg: 13.2 − 8.0 = 5.2. At 1 mg: 22.7 − 16.8 = 5.9. At 2 mg: 26.1 − 26.1 = 0. So the gap is about 5 to 6 units at the two lower doses and disappears at the highest.

What the answer means. Put together: "Tooth length rises with vitamin C dose; orange juice gives longer teeth than ascorbic acid at low doses, but the difference disappears at 2 mg a day." When the effect of one factor depends on the level of another, as the supplement effect depends on dose here, statisticians call it an interaction. These are differences between group means only; whether they are larger than chance would produce is a question for a statistical test.

Go deeper: Anscombe's quartet

In 1973 the statistician Francis Anscombe published four small datasets, each of 11 pairs of x and y values, with almost the same summary numbers: the mean of x is 9, the mean of y about 7.5, the correlation about 0.82, and the best-fitting straight line is close to y = 3 + 0.5x. Plotted, they look nothing alike. One is a loose straight-line cloud, one a smooth curve, one a perfect line with a single outlier, and one a vertical stack of points whose slope is set entirely by one far-away point.

seaborn includes the data, so you can see this for yourself: anscombe = sns.load_dataset("anscombe"), then sns.lmplot(data=anscombe, x="x", y="y", col="dataset", col_wrap=2). load_dataset downloads the file from seaborn's online collection, so it needs an internet connection. The lesson from the quartet is the same as this one: check any table of summary numbers against a plot of the data behind it.

The data come from Crampton (1947), "The growth of the odontoblasts of the incisor tooth as a criterion of the vitamin C intake of the guinea pig", Journal of Nutrition 33(5), 491–504; the version used here is the ToothGrowth dataset that comes with R. The reasoning behind preferring points to bars, pies and 3D comes from Cleveland & McGill (1984), "Graphical perception", Journal of the American Statistical Association 79, 531–554. In their experiments, people judged values most accurately from positions along a common scale, less accurately from lengths and angles, and least accurately from areas, volumes and shading. The ranking describes average accuracy for simple judgements, so treat it as a guide for choosing charts, not a law.

Showing every point works while there are few of them. With hundreds of values per group the dots merge into a solid block, and a summary of the shape works better. The next lesson, Showing distributions, compares the main ways of drawing that shape and what each one hides.

Key point

With fewer than about 30 points per group, show every point. Readers can then judge the spread, the overlap and any outliers for themselves.

A small example shows why. Five measurements of 1, 2, 3, 4 and 40 have a mean of 50 ÷ 5 = 10. A bar of height 10 suggests a typical value of about 10, yet four of the five values are below 5, and the mean comes almost entirely from one measurement. Drawn as points, the single high value is obvious at once, and the reader can ask whether it is a real result or an error.

Further reading · Module 2Weissgerber et al. 2015: why bar charts hide the data. · All reading for this course

Check your understanding

1. Which chart shows how two continuous measures relate?

2. Ten mice per group. What should the figure show?

3. Why does okabe name each colour by group?

Up next

Lesson 2

Showing distributions

Ask BioTutor

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