Lesson 4 of 9
Module 2 · Figures that tell the truth
About 1 in 12 men and 1 in 200 women have a colour vision deficiency, most often red–green. Choosing the right kind of palette makes figures readable for them and clearer for everyone.
Before you start. This lesson uses the libraries loaded in Choosing the right chart. If you open a new notebook, run this setup cell first. If seaborn prints a DeprecationWarning or PendingDeprecationWarning, it comes from the library, not from your code, and you can ignore it.
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns
Match the palette to the data
A colour vision deficiency means that one type of the eye's colour-sensing cells, the cones, is missing or responds differently, so some colours that look distinct to most people look alike. In the commonest forms, reds and greens are hard to tell apart. These forms are inherited on the X chromosome, which is why they are much more common in men. The fix is less about avoiding particular colours than about choosing the right kind of palette for the data, which the table sets out.
Most people have three types of cone, most sensitive to long (red), medium (green) and short (blue) wavelengths of light. The common red–green deficiencies affect the long or medium cones; a blue–yellow deficiency, which affects the short cones, is much rarer. In all of them, colours that differ mainly in hue, such as a medium red and a medium green, can collapse into one. Colours that also differ in lightness, how light or dark they are, stay apart. That is the single most useful idea in this lesson: a palette whose colours differ in lightness as well as hue works for almost everyone.
The kind of palette matters for every reader, not only those with a colour vision deficiency. A palette that does not match the data says something false. Colouring three unordered cell types from light to dark suggests that one type is "more" than another. Colouring raw expression, which has no meaningful middle, from blue through white to red suggests a threshold at the white point that the data do not have.
How to read the table below
Find the row that describes your data, not your favourite colours. The middle column names the kind of palette, and the right column gives tested choices. The three kinds are:
- Categorical: clearly different colours with no order, for groups such as treatments or cell types. The Okabe–Ito palette is a set of eight colours, listed as hex codes, chosen to stay distinguishable for people with the common colour vision deficiencies.
- Sequential: one direction from light to dark, for values from low to high. viridis and cividis are designed to be perceptually uniform, meaning equal steps in the data look like equal steps in colour, and their lightness changes steadily, so they still read in greyscale. cividis was designed specifically for readers with colour vision deficiency.
- Diverging: two directions away from a meaningful middle, such as zero change. RdBu is red–white–blue; PRGn is purple–white–green.
Two questions settle most cases. Do the values have an order? If not, use a categorical palette. If they do, is there a meaningful middle, such as zero change or the average? If so, use a diverging palette centred on it; if not, a sequential one. Cell types in a single-cell experiment are categorical, sequencing depth per sample is sequential, and log2 fold changes between treated and control are diverging.
Categorical palettes have a practical limit. Beyond about seven or eight colours, readers can no longer match a colour in the plot to its entry in the legend, however well the colours are chosen. With more groups than that, merge the small ones into "other", split the figure into panels, or label the groups directly on the plot.
| Data | Palette type | Good choices |
|---|---|---|
| Groups with no order (treatment, cell type) | Categorical | Okabe–Ito: #E69F00 #56B4E9 #009E73 #F0E442 #0072B2 #D55E00 #CC79A7 #000000 |
| Low to high (expression, counts) | Sequential | viridis, cividis |
| Below and above a meaningful middle (fold change, z-score) | Diverging, centred on the middle | Blue–white–red (RdBu), purple–green (PRGn) |
The code below draws the same genes three ways, to show the difference. A fold change is the ratio of a value in one condition to its value in another, usually shown on a log2 scale, so that 0 means no change. A z-score, as in Figures with matplotlib and seaborn, says how many standard deviations a value lies above or below its row's average, so 0 means "average".
expr = pd.read_csv("expression_example.csv", index_col="gene")
z = expr.sub(expr.mean(axis=1), axis=0).div(expr.std(axis=1), axis=0) # z-score each gene
fig, axes = plt.subplots(1, 3, figsize=(11, 4.2))
sns.heatmap(z.iloc[:12], cmap="jet", ax=axes[0], cbar_kws={"shrink": 0.7})
sns.heatmap(z.iloc[:12], cmap="RdBu_r", center=0, vmin=-2, vmax=2, ax=axes[1], cbar_kws={"shrink": 0.7})
sns.heatmap(expr.iloc[:12], cmap="viridis", ax=axes[2], cbar_kws={"shrink": 0.7})
for ax, t in zip(axes, ["Rainbow (avoid)", "Diverging, centred on 0", "Sequential: viridis"]):
ax.set_title(t, loc="left", fontsize=11); ax.set_xlabel(""); ax.set_ylabel("")
plt.tight_layout()What this does
index_col="gene"uses thegenecolumn as the row labels, so each row is named by its gene and every other column is a sample.- The z-score line works in two steps.
expr.mean(axis=1)is each gene's mean across the samples (axis=1means "along each row"), and.sub(…, axis=0)subtracts it from every value in that row..div(expr.std(axis=1), axis=0)then divides each row by its own standard deviation. This is the same calculation thatz_score=0did for you inclustermap. plt.subplots(1, 3, …)makes three plots side by side..iloc[:12]takes the first 12 rows by position, using the same slicing rule as strings.- Left: the z-scores in jet, a rainbow colour scale. Middle: the same z-scores in RdBu_r, with
center=0putting white at zero andvmin=-2, vmax=2fixing the ends of the scale. Right: the original values, not z-scored, in viridis. - The
_rat the end of RdBu_r reverses the colour map. Plain RdBu runs from red at low values to blue at high values; reversed, low is blue and high is red, the order most readers expect for "down" and "up". Forgetting the_ris a common pitfall: the figure still looks fine, but every increase is drawn in blue. cbar_kws={"shrink": 0.7}makes each colour bar 70% of the plot's height. The loop sets the titles and removes the axis labels, since the gene and sample names already label the rows and columns.
Reading the three heatmaps
The rainbow scale does not change in lightness evenly: yellow and cyan look much brighter than the blue and red around them. Your eye reads those bright bands as edges, so smooth changes in the data look like sharp boundaries that are not there. In the diverging version, colour carries direction: red is above the gene's average, blue below, white near it, and the pattern in the treated samples is easy to see. The viridis version answers a different question, how high each gene is overall, which the z-scores deliberately removed. Choose the palette for the question.
The z-scores carry their own pitfall on real data. Because each gene is scaled by its own standard deviation, a gene measured at a handful of reads and a gene measured at thousands both span the same range of colours. A noisy, barely expressed gene can then look as striking as a strongly expressed one. For RNA-seq data, heatmaps of z-scores are usually drawn after filtering out genes with very low counts, and a sequential heatmap of the unscaled values, like the right panel, is a useful check on which genes are expressed at all.
Worked example · centring a diverging scale
if the limits were −1 and 3, white would sit at +1 and “no change” would look like an increase
Step by step. A diverging scale puts white halfway between its two limits. With limits −2 and 2, the halfway point is (−2 + 2) ÷ 2 = 0, the value that means "at the gene's average". The data run from −2.01 to 2.00, so symmetric limits of −2 and 2 cover almost all of it; the single value of −2.01 simply takes the darkest blue. With limits −1 and 3, the halfway point is (−1 + 3) ÷ 2 = 1.
What the answer means. White would then mark +1 instead of 0, so the colours would no longer mean what readers assume: white, which everyone reads as "no change", would stand for a value one standard deviation above average. Many programs choose limits from the smallest and largest values in the data, which are rarely symmetric. That is why the code sets center=0 and equal limits on both sides on purpose.
Go deeper: colour-blind-safe defaults in seaborn
Instead of typing hex codes for every plot, you can make the Okabe–Ito colours the default once, at the top of a notebook. Store them in a list, okabe_ito = ["#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7", "#000000"], and run sns.set_palette(okabe_ito). Every later plot that colours by group then takes the colours in that order. A dictionary, as in Choosing the right chart, is still safer when a group must keep the same colour in every figure.
seaborn also has its own perceptually uniform scales: "rocket" and "mako" are sequential, and "vlag" and "icefire" are diverging. Its built-in "colorblind" palette is a different set of colours made with the same aim as Okabe–Ito. One caution: the Okabe–Ito yellow, #F0E442, is hard to see on a white background, so use it for filled shapes rather than thin lines or small text.
The Okabe–Ito palette comes from Masataka Okabe and Kei Ito's online guide "Color Universal Design" (first published around 2002). Crameri, Shephard & Heron (2020), "The misuse of colour in science communication", Nature Communications 11, 5444, shows how rainbow scales such as jet distort data and shut out readers with colour vision deficiency. cividis is described by Nuñez, Anderton & Renslow (2018) in PLOS ONE. Prevalence figures depend on the population: red–green colour vision deficiency affects roughly 8% of men and 0.5% of women of Northern European ancestry, and fewer in many other populations studied. Colour-blindness simulators model typical forms only; they cannot show exactly what any one reader sees.
Key point
Never use colour alone to carry meaning. Add shapes, labels or direct annotation, and check your figure in greyscale or with a colour-blindness simulator.
A line plot of two treatment groups over time is a good example. If one line is red and the other green, some readers see two similar lines. Make one line solid and the other dashed, use different marker shapes, and write the group name at the end of each line instead of in a separate legend. The figure then works in colour, in greyscale, on a poor projector and for every reader.
Checking takes a minute. Save the figure, open it and switch your screen or image viewer to greyscale, or print it in black and white. If two groups become the same grey, or a sequential scale no longer runs smoothly from light to dark, change the colours or add a second cue such as shape. A colour scale is also a kind of axis: its limits decide which values look extreme, just as the limits of a y axis do. The next lesson, Honest axes and scales, looks at those choices.
Further reading · Module 2Weissgerber et al. 2015: why bar charts hide the data. · All reading for this course
Check your understanding
1. Which palette suits log2 fold changes?
2. Why avoid the rainbow (jet) palette?
3. Which pair is hardest for the most common colour vision deficiency?
Up next
Lesson 5
Honest axes and scales