library(tidyverse) # ggplot2, dplyr, tidyr, readr and friends
library(here) # file paths that start at the project folder
library(patchwork) # put plots side by side with +1 How to read (and plan) a genomics figure
You see a fancy figure in a paper and want to make something similar. Where do you start? Here’s the good news: almost every figure in a genomics paper is built from a handful of basic plots. If you can name what’s on the x-axis, what’s on the y-axis and the plot type, you can rebuild it. And you can plan your own figures the same way, before you write a line of code.
In this lesson you’ll learn
- the six plot types behind most genomics figures
- how to break a figure into x, y and plot type, and what data frame it needs
- why a boxplot of 5 samples can fool you, and what to draw instead
- when to use a sequential color map and when to use a diverging one
- why you plot your data before you trust a correlation
- why making the plot is only 10% of the work
1.1 Load the packages and the data
Let’s load the packages we need.
Our data is RNA-seq expression from The Cancer Genome Atlas (TCGA): one row per sample, one column per gene, values in TPM (transcripts per million). Let’s read it in.
tcga <- read_csv(here("data", "TCGA_cancer_genes_expression.csv"))
dim(tcga)[1] 11348 25
That’s 11,348 samples and 25 columns: a sample id with no header (readr names it ...1), 20 genes, the TCGA barcode, TCGA’s own sample type, the study (cancer type) and a simplified sample_type. Let’s count.
count(tcga, sample_type)# A tibble: 4 × 2
sample_type n
<chr> <int>
1 cancer 10021
2 metastatic 394
3 normal 740
4 <NA> 193
n_distinct(tcga$study)[1] 33
We have 10,021 primary tumors (cancer), 394 metastases, 740 normal tissue samples and 193 without a label, from 33 cancer types. Many of the 20 genes are targets of antibody-drug conjugates and other cell-surface drugs: TACSTD2 is TROP2, ERBB2 is HER2.
1.2 Six plot types cover 90% of genomics figures
If you read genomics papers, most of the figures fall into a few categories:
- Scatter plot
- Bar plot
- Line plot
- Boxplot or violin plot
- Histogram
- Heatmap
If you master those six types of figures, you can reproduce 90% of the figures in any genomics paper. Watch this:
Master ggplot2 for the first five and ComplexHeatmap for heatmaps, and you can make most bioinformatics figures. That’s the plan for this course. Lesson 2 builds the first five on this TCGA table. Lesson 3 is all heatmaps, because a heatmap hides more decisions than any other plot. Lesson 4 shows that single-cell figures are the same plot types in disguise: a UMAP is a scatter plot, and a dot plot is a heatmap.
1.3 Break a figure into x, y and plot type
When you see a figure you want to recreate, ask three questions:
- What’s on the x-axis?
- What’s on the y-axis?
- What plot type is it?
Then, before you plot anything, get the data structure right. For ggplot2, everything goes into a single data frame, and you ask: which column maps to x, which to y, and which columns control color, shape or size?
Take the single-cell dot plot: genes on one axis, clusters on the other, color is the average expression, and dot size is the proportion of cells in the cluster with nonzero expression. In ggplot2 those four columns go in one data frame. In ComplexHeatmap you prepare two matrices of the same shape, one for color and one for size.
- Clustered dotplot for single-cell RNAseq: the dot plot built both ways.
Let’s practice. Say you want to compare TROP2, HER2 and NECTIN4 between breast tumors and normal breast tissue. The plan:
- x: the gene
- y: expression, as log2(TPM + 1)
- fill color: tumor or normal
- plot type: boxplot
Here’s the catch: our table has one column per gene, but the plan needs one column called gene. We need the long format, one row per sample per gene. pivot_longer() does that.
brca_long <- tcga %>%
filter(study == "BRCA", sample_type %in% c("cancer", "normal")) %>%
select(sample_type, TACSTD2, ERBB2, NECTIN4) %>%
pivot_longer(cols = c(TACSTD2, ERBB2, NECTIN4),
names_to = "gene", values_to = "tpm")
head(brca_long)# A tibble: 6 × 3
sample_type gene tpm
<chr> <chr> <dbl>
1 cancer TACSTD2 105.
2 cancer ERBB2 98.3
3 cancer NECTIN4 59.1
4 cancer TACSTD2 307.
5 cancer ERBB2 98.3
6 cancer NECTIN4 120.
Each sample now appears three times, once per gene, and every item in the plan has its own column.
ggplot(brca_long, aes(x = gene, y = log2(tpm + 1), fill = sample_type)) +
geom_boxplot()
Why log2(tpm + 1)? TPM values are skewed: most are small and a few are huge. The log squeezes the huge values so you can see the rest, and the + 1 keeps a zero from turning into minus infinity. Let’s check the medians behind the boxes.
brca_long %>%
group_by(gene, sample_type) %>%
summarise(n = n(), median = median(log2(tpm + 1)), .groups = "drop")# A tibble: 6 × 4
gene sample_type n median
<chr> <chr> <int> <dbl>
1 ERBB2 cancer 1127 6.27
2 ERBB2 normal 112 5.70
3 NECTIN4 cancer 1127 5.52
4 NECTIN4 normal 112 4.89
5 TACSTD2 cancer 1127 8.03
6 TACSTD2 normal 112 8.36
ERBB2 and NECTIN4 are higher in tumors (6.27 vs 5.70 and 5.52 vs 4.89). TACSTD2 is high in both, and a bit higher in normal breast (8.36 vs 8.03). Don’t worry about every piece of the ggplot2 code yet; lesson 2 goes through it line by line. The point is the order of work: plan x, y and the plot type, shape the data frame to match, and the plot itself is the easy part.
1.4 A boxplot of five samples can fool you
A boxplot summarizes a group with a few numbers: the median (the middle line), the first and third quartiles (the box) and the whiskers. With 1,000 samples that summary is stable. With 5 it is not. I saw this example from Chenxin Li: draw small samples from the same distribution again and again, and watch the boxes jump. Let’s do it with real data.
brca <- tcga %>%
filter(study == "BRCA", sample_type == "cancer")
nrow(brca)[1] 1127
Let’s shuffle the 1,127 breast tumors and cut them into 10 groups of 5, then do it again with 10 groups of 100. All the groups come from the same tumors, so in a perfect world every box would look the same.
set.seed(123)
small <- brca %>%
slice_sample(n = 50) %>%
mutate(draw = rep(1:10, each = 5), size = "5 tumors per draw")
large <- brca %>%
slice_sample(n = 1000) %>%
mutate(draw = rep(1:10, each = 100), size = "100 tumors per draw")
draws <- bind_rows(small, large)ggplot(draws, aes(x = factor(draw), y = log2(ERBB2 + 1))) +
geom_boxplot() +
facet_wrap(~ size) +
labs(x = "Random draw", y = "ERBB2, log2(TPM + 1)")
Let’s put a number on it: the lowest and highest median across the 10 draws.
draws %>%
group_by(size, draw) %>%
summarise(median = median(log2(ERBB2 + 1)), .groups = "drop") %>%
group_by(size) %>%
summarise(lowest = min(median), highest = max(median))# A tibble: 2 × 3
size lowest highest
<chr> <dbl> <dbl>
1 100 tumors per draw 6.20 6.45
2 5 tumors per draw 5.51 7.38
Same tumors, same gene. With 100 tumors per draw, the median stays between 6.20 and 6.45. With 5 per draw, it swings from 5.51 to 7.38, almost 2 units on the log2 scale (about 3.7-fold). Label two small draws “treated” and “control” and you have an effect that is pure chance.
So what do you do with small groups? Show the points. A real case: TCGA has 304 cervical cancer (CESC) tumors and only 3 normal samples.
cesc <- tcga %>%
filter(study == "CESC", sample_type %in% c("cancer", "normal"))
count(cesc, sample_type)# A tibble: 2 × 2
sample_type n
<chr> <int>
1 cancer 304
2 normal 3
Let’s draw the boxplot alone, then the same boxplot with every sample on top.
p_box <- ggplot(cesc, aes(x = sample_type, y = log2(TACSTD2 + 1))) +
geom_boxplot() +
ggtitle("Boxplot only")
p_points <- ggplot(cesc, aes(x = sample_type, y = log2(TACSTD2 + 1))) +
geom_boxplot(outlier.shape = NA) +
geom_jitter(width = 0.2, alpha = 0.4) +
ggtitle("Boxplot plus every sample")
p_box + p_points
On the left, the normal box looks as trustworthy as the tumor box. On the right, it’s three dots that don’t agree. Let’s print them.
cesc %>%
filter(sample_type == "normal") %>%
mutate(log2_tpm = log2(TACSTD2 + 1)) %>%
select(tcga.tcga_barcode, log2_tpm)# A tibble: 3 × 2
tcga.tcga_barcode log2_tpm
<chr> <dbl>
1 TCGA-MY-A5BF-11A-11R-A26T-07 7.15
2 TCGA-HM-A3JJ-11A-12R-A21T-07 3.92
3 TCGA-FU-A3EO-11A-13R-A213-07 2.80
One normal sits at 7.15, within the spread of the tumors, and the other two are much lower, at 3.92 and 2.80. geom_jitter() spreads the points sideways a little so they don’t pile up, and outlier.shape = NA stops the boxplot from drawing its outliers a second time. The + between the two plots comes from patchwork.
A box drawn from 3 samples looks exactly like a box drawn from 300. When a group is small, overlay the points (or use a raincloud plot) and put n in the axis label or the figure legend.
1.5 Sequential or diverging: pick the color map for your data
In a heatmap, color encodes meaning, and the wrong color map gives you a misleading heatmap. Categorical data (cancer type, cell type) gets different hues. Quantitative data (expression) gets lightness, darker for more, and comes in two cases:
- All values positive (TPM, counts): a sequential map, like white to dark blue.
- Values on both sides of a meaningful zero (z-scores, log fold changes): a diverging map, like blue to white to red, with white at zero. Hue shows the direction, saturation shows how far from zero.
Let’s make a small table: the median expression of six genes in tumors from six cancer types, plus a z-score for each gene.
genes <- c("ERBB2", "MSLN", "FOLR1", "CEACAM5", "FOLH1", "EGFR")
studies <- c("BRCA", "COAD", "GBM", "MESO", "OV", "PRAD")
med <- tcga %>%
filter(sample_type == "cancer", study %in% studies) %>%
select(study, all_of(genes)) %>%
pivot_longer(cols = all_of(genes), names_to = "gene", values_to = "tpm") %>%
group_by(gene, study) %>%
summarise(log2_tpm = median(log2(tpm + 1)), .groups = "drop") %>%
group_by(gene) %>%
mutate(z = (log2_tpm - mean(log2_tpm)) / sd(log2_tpm)) %>%
ungroup()
head(med)# A tibble: 6 × 4
gene study log2_tpm z
<chr> <chr> <dbl> <dbl>
1 CEACAM5 BRCA 2.09 -0.0416
2 CEACAM5 COAD 10.9 2.00
3 CEACAM5 GBM 0 -0.527
4 CEACAM5 MESO 0 -0.527
5 CEACAM5 OV 0.0217 -0.522
6 CEACAM5 PRAD 0.605 -0.386
The z column says how many standard deviations each cancer type sits above (positive) or below (negative) that gene’s average across the six. So z has a meaningful zero. Let’s give it to ggplot2 with the default colors.
ggplot(med, aes(x = study, y = gene, fill = z)) +
geom_tile()
Where is zero? You can’t tell. Below average and above average are two shades of the same blue, so the one boundary that matters in a z-score is invisible.
ggplot2’s default continuous fill runs from dark blue (lowest) to light blue (highest). It knows nothing about zero, and it makes the highest value the lightest tile. For data centered on zero, ask for a diverging map with scale_fill_gradient2(midpoint = 0).
Now let’s give each kind of value its own map.
p_seq <- ggplot(med, aes(x = study, y = gene, fill = log2_tpm)) +
geom_tile(color = "white") +
scale_fill_gradient(low = "white", high = "darkblue", limits = c(0, NA)) +
ggtitle("Sequential: median log2(TPM + 1)")
p_div <- ggplot(med, aes(x = study, y = gene, fill = z)) +
geom_tile(color = "white") +
scale_fill_gradient2(low = "blue", mid = "white", high = "red", midpoint = 0) +
ggtitle("Diverging: z-score per gene")
p_seq + p_div
The left panel shows absolute levels. Let’s list the five darkest tiles.
med %>%
slice_max(log2_tpm, n = 5)# A tibble: 5 × 4
gene study log2_tpm z
<chr> <chr> <dbl> <dbl>
1 CEACAM5 COAD 10.9 2.00
2 MSLN MESO 9.10 1.22
3 MSLN OV 8.95 1.19
4 FOLR1 OV 8.17 1.98
5 FOLH1 PRAD 7.93 2.00
CEACAM5 in colon cancer (COAD) is the highest at 10.9, then MSLN in mesothelioma (MESO, 9.10) and ovarian cancer (OV, 8.95), FOLR1 in OV (8.17) and FOLH1 (PSMA) in prostate cancer (PRAD, 7.93).
A sequential map can be anchored two ways: lightest = 0, or lightest = the smallest value you have. ggplot2 uses your data’s range by default. I added limits = c(0, NA) to pin white to zero TPM, because zero means something here: the gene is off. Use the observed range when the variation among your values matters more.
The right panel answers a different question: where is each gene unusually high or low? Let’s compare two genes.
med %>%
filter(gene %in% c("ERBB2", "MSLN")) %>%
arrange(gene, desc(z))# A tibble: 12 × 4
gene study log2_tpm z
<chr> <chr> <dbl> <dbl>
1 ERBB2 BRCA 6.27 1.29
2 ERBB2 PRAD 5.81 0.717
3 ERBB2 COAD 5.45 0.268
4 ERBB2 OV 5.07 -0.203
5 ERBB2 MESO 4.83 -0.502
6 ERBB2 GBM 3.98 -1.57
7 MSLN MESO 9.10 1.22
8 MSLN OV 8.95 1.19
9 MSLN COAD 4.45 0.0875
10 MSLN GBM 0.927 -0.774
11 MSLN PRAD 0.699 -0.830
12 MSLN BRCA 0.441 -0.893
ERBB2 in BRCA (z = 1.29) is about as red as MSLN in MESO (z = 1.22), even though MSLN spans 0.44 to 9.10 across these cancer types and ERBB2 only 3.98 to 6.27. Scaling each gene throws away its absolute level. Neither panel is wrong. Pick the one that answers your question and say which one it is. Lesson 3 goes much deeper into when to scale.
1.6 Plot your data before you trust a number
One outlier can break your whole analysis. Let’s compute the correlation between TACSTD2 (TROP2) and NECTIN4 in adrenocortical carcinoma (ACC) tumors.
acc <- tcga %>%
filter(study == "ACC", sample_type == "cancer")
nrow(acc)[1] 79
cor(acc$TACSTD2, acc$NECTIN4)[1] 0.984469
A Pearson correlation of 0.98 across 79 tumors. Stop here and you might write “TROP2 and NECTIN4 are tightly co-expressed in adrenocortical carcinoma.” Now let’s plot it.
ggplot(acc, aes(x = TACSTD2, y = NECTIN4)) +
geom_point()
78 dots piled up in the bottom-left corner and one dot far away in the top right. That one sample is the whole correlation. Let’s look at it and recompute without it.
acc %>%
slice_max(TACSTD2, n = 3) %>%
select(tcga.tcga_barcode, TACSTD2, NECTIN4, MUC1)# A tibble: 3 × 4
tcga.tcga_barcode TACSTD2 NECTIN4 MUC1
<chr> <dbl> <dbl> <dbl>
1 TCGA-OR-A5JB-01A-11R-A29S-07 221. 16.9 117.
2 TCGA-P6-A5OG-01A-22R-A29S-07 25.4 0.0728 2.02
3 TCGA-OR-A5JO-01A-11R-A29S-07 13.9 0 0.502
acc_without <- acc %>%
filter(TACSTD2 < max(TACSTD2))
cor(acc_without$TACSTD2, acc_without$NECTIN4)[1] -0.02113363
Sample TCGA-OR-A5JB has 221 TPM of TACSTD2, 16.9 of NECTIN4 and 117 of MUC1; the next two have 25 TPM of TACSTD2 or less. Without it, the correlation is -0.02. The story disappears. A rank-based (Spearman) correlation barely notices one extreme point:
cor(acc$TACSTD2, acc$NECTIN4, method = "spearman")[1] 0.07743026
It’s 0.08 on all 79 tumors. Is that sample a tumor with an unusual epithelial program, contaminating tissue, or a labeling problem? The plot can’t tell you, but it told you where to look. The 0.98 never would have. One sample out of 79 made a correlation of 0.98. Plot before you publish.
Itai Yanai and Martin Lercher showed how easy it is to skip this step. They gave students a made-up dataset of daily steps and body mass index (BMI); plot one against the other and a gorilla waves at you. Students without a specific hypothesis were almost five times more likely to find the gorilla (A hypothesis is a liability, Genome Biology 2020).
My rule: if a result surprises me, I stop and plot it again. Usually the surprise is pointing at something real: a swapped sample, a wrong label, or one strange tumor like TCGA-OR-A5JB.
One more trap when you have thousands of points: ggplot2 draws them in row order, so later points cover earlier ones, and what you see is the top layer, not the crowd. Lesson 4 shows what that does to a single-cell feature plot.
1.7 Making the plot is 10% of the work
Creating a figure as a bioinformatician? 10% making the plot. 90% changing fonts, colors, labels and layout. Your first draft works. Then the feedback comes in from collaborators: increase the font size, change the axis label, use blue instead of orange, add sample names, flip the heatmap. That’s normal. Expect several rounds, and make them cheap:
- Keep the figure in a script and save it with
ggsave(). Avoid manual tweaks in Illustrator if you can, so a revision is a one-line change and a rerun. - Version your files, like
fig1_v3.pdf. - Build multi-panel figures with patchwork. It arranges ggplots like LEGO blocks; you already used
p_box + p_points.
Let’s polish the cervical cancer plot: real labels, n on the axis, a bigger font, and a saved file.
p_final <- ggplot(cesc, aes(x = sample_type, y = log2(TACSTD2 + 1))) +
geom_boxplot(outlier.shape = NA) +
geom_jitter(width = 0.2, alpha = 0.4, size = 1) +
scale_x_discrete(labels = c(cancer = "Tumor\n(n = 304)", normal = "Normal\n(n = 3)")) +
labs(x = NULL, y = "TACSTD2 (TROP2)\nlog2(TPM + 1)", title = "Cervical cancer, TCGA") +
theme_classic(base_size = 14)
p_final
ggsave(file.path(tempdir(), "fig1_v1.pdf"), p_final, width = 4.5, height = 4)scale_x_discrete(labels = ...) renames the groups on the axis without touching the data, and \n breaks a label into two lines. theme_classic(base_size = 14) sets every font size from one number. ggsave() writes the file at an exact width and height in inches. I save to tempdir() to keep the course folder clean; in your project, use a figures/ folder.
Before a figure leaves my laptop, I check four things: can I read every label at the printed size, does it still work in grayscale, is there room to breathe, and can someone follow it without the caption?
Don’t settle for default heatmap colors. Zuguang Gu, who wrote ComplexHeatmap, explains perceptually uniform HCL color maps in Support HCL colormaps in ComplexHeatmap. For multi-panel layouts, keep the patchwork assembly guide open.
1.8 Your turn
1. Plan, then plot. Before writing code, write down x, y and the plot type for “EPCAM in colon cancer (COAD) tumors vs normal colon, every sample visible.” Then make it. How many normal samples are there, and which group has the higher median log2(TPM + 1)?
The plan: x = sample_type, y = log2(EPCAM + 1), plot type = boxplot with jittered points on top.
coad <- tcga %>%
filter(study == "COAD", sample_type %in% c("cancer", "normal"))
coad %>%
group_by(sample_type) %>%
summarise(n = n(), median = median(log2(EPCAM + 1)))# A tibble: 2 × 3
sample_type n median
<chr> <int> <dbl>
1 cancer 504 9.60
2 normal 41 9.78
ggplot(coad, aes(x = sample_type, y = log2(EPCAM + 1))) +
geom_boxplot(outlier.shape = NA) +
geom_jitter(width = 0.2, alpha = 0.4)
There are 41 normal samples (and 504 tumors). The medians are almost the same, 9.78 in normal colon and 9.60 in tumors: EPCAM marks epithelial cells, and the lining of a normal colon is epithelium too.
2. Small groups. Which cancer types have fewer than 5 normal samples? Then plot TACSTD2 in pancreatic cancer (PAAD) tumors vs normals with every sample visible. Does any normal sample stand out?
tcga %>%
filter(sample_type == "normal") %>%
count(study) %>%
filter(n < 5)# A tibble: 6 × 2
study n
<chr> <int>
1 CESC 3
2 PAAD 4
3 PCPG 3
4 SARC 2
5 SKCM 1
6 THYM 2
paad <- tcga %>%
filter(study == "PAAD", sample_type %in% c("cancer", "normal"))
ggplot(paad, aes(x = sample_type, y = log2(TACSTD2 + 1))) +
geom_boxplot(outlier.shape = NA) +
geom_jitter(width = 0.2, alpha = 0.4)
Six cancer types: CESC (3), PAAD (4), PCPG (3), SARC (2), SKCM (1) and THYM (2). In PAAD, three of the four normals sit between about 7.8 and 9.1 and one sits near 1.1. With four points, that one sample decides where the bottom of the box goes.
3. Find the outlier. In kidney chromophobe (KICH) tumors, compute the Pearson correlation between FOLR1 and DLL3, plot it, then recompute it without the sample with the highest FOLR1.
kich <- tcga %>%
filter(study == "KICH", sample_type == "cancer")
cor(kich$FOLR1, kich$DLL3)[1] 0.948383
ggplot(kich, aes(x = FOLR1, y = DLL3)) +
geom_point()
kich %>%
slice_max(FOLR1, n = 1) %>%
select(tcga.tcga_barcode, FOLR1, DLL3)# A tibble: 1 × 3
tcga.tcga_barcode FOLR1 DLL3
<chr> <dbl> <dbl>
1 TCGA-KM-8639-01A-11R-2403-07 836. 9.13
kich_without <- kich %>%
filter(FOLR1 < max(FOLR1))
cor(kich_without$FOLR1, kich_without$DLL3)[1] -0.0732222
The correlation is 0.95 across 66 tumors and -0.07 without one sample, TCGA-KM-8639, which has 836 TPM of FOLR1 and 9.13 of DLL3. Same lesson as ACC: one point made the whole correlation.
1.9 Take-home points
- Six plot types (scatter, bar, line, boxplot or violin, histogram, heatmap) cover most genomics figures.
- To recreate a figure, name the x-axis, the y-axis and the plot type, then shape one data frame (often with
pivot_longer()) so every aesthetic has its own column. - Boxplots of a few samples are unstable. When n is small, show every point and report n.
- All-positive values get a sequential color map; values centered on zero get a diverging one with white at zero.
- Scaling each gene shows relative patterns and hides absolute levels. Say which one you plotted.
- Plot before you trust a number. One sample out of 79 made a correlation of 0.98.
- Making the plot is 10% of the work. Keep figures in scripts, save them with
ggsave(), expect revisions.