Published on
13 min read

How to make a gene expression heatmap in R (that actually looks good)

Authors
  • avatar
    Name
    BioTech Bench
Table of contents

This is Arc 2, Part 9 of the R for Biologists series.

Updated November 2026: this post now uses the real airway RNA-seq counts (Himes et al., 2014), and every output and figure was generated by running the code shown. An earlier version used a hand-typed matrix of illustrative values.

The table you can't read

Post 8 showed how to turn raw counts into log2 CPM on a small 10-gene example. Real RNA-seq gives you that for tens of thousands of genes, and reading a pattern out of a table of numbers across even 30 genes and 8 samples is not something human visual systems are good at.

A heatmap is the fix. Color replaces number, and the eye picks up patterns instantly — which genes go up together, which go down, which samples cluster with which. Every RNA-seq paper has at least one. This post builds one from real data, step by step, until it is publication-ready.

What you'll learn

  • What a heatmap encodes: color = expression level, rows = genes, columns = samples
  • What the dendrogram is actually showing: hierarchical clustering, distance, linkage
  • How to build a minimal heatmap with pheatmap
  • How to upgrade it: RdBu color palette, z-score row scaling, sample annotations for treatment and donor
  • How to control clustering: distance metric, linkage method, cutree_rows for visual gaps
  • Why a heatmap of hand-picked genes is a display, not evidence

Setup

Install the packages if you haven't already. airway (the dataset) and edgeR (for cpm()) come from Bioconductor:

install.packages(c("pheatmap", "RColorBrewer", "BiocManager")) # skip if already installed
BiocManager::install(c("airway", "edgeR"))                     # skip if already installed

Load them:

library(airway)
library(edgeR)
library(pheatmap)
library(RColorBrewer)

The data: real airway smooth muscle RNA-seq

We're continuing with the dexamethasone experiment from Posts 7 and 8: human airway smooth muscle cells treated with dexamethasone (a glucocorticoid) versus untreated controls. This time we use the real counts, which ship with the Bioconductor airway package. Cells from four donors were each split into an untreated and a treated dish, giving 8 samples.

data("airway")
counts <- assay(airway)
dim(counts)
[1] 63677     8

63,677 genes (Ensembl IDs) by 8 samples. The sample table tells us which donor and treatment each column is:

samples <- as.data.frame(colData(airway))[, c("cell", "dex")]
samples
              cell   dex
SRR1039508  N61311 untrt
SRR1039509  N61311   trt
SRR1039512 N052611 untrt
SRR1039513 N052611   trt
SRR1039516 N080611 untrt
SRR1039517 N080611   trt
SRR1039520 N061011 untrt
SRR1039521 N061011   trt

SRR numbers are unreadable on a plot, so rename the columns to Treatment_Donor, then reorder so the four controls come first and the four dex samples second, in the same donor order:

colnames(counts) <- paste0(ifelse(samples$dex == "trt", "Dex", "Ctrl"), "_", samples$cell)
counts <- counts[, c(1, 3, 5, 7, 2, 4, 6, 8)]
colnames(counts)
[1] "Ctrl_N61311"  "Ctrl_N052611" "Ctrl_N080611" "Ctrl_N061011" "Dex_N61311"
[6] "Dex_N052611"  "Dex_N080611"  "Dex_N061011"

Normalize to log2 CPM exactly as in Post 8:

log2cpm <- log2(cpm(counts) + 1)

Choosing 30 genes to show

A heatmap of all 63,677 genes would be a smear, so we pick genes. We keep genes that are reasonably expressed in every sample (log2 CPM of at least 3, roughly 7 counts per million), then rank them by their average change with dex. Because each donor has a control and a dex sample, we compute the change within each donor and average the four differences:

expressed <- apply(log2cpm, 1, min) >= 3
sum(expressed)
[1] 9155
ctrl   <- log2cpm[expressed, 1:4]
dex    <- log2cpm[expressed, 5:8]
change <- rowMeans(dex - ctrl)   # columns are in the same donor order

top_up   <- names(sort(change, decreasing = TRUE))[1:15]
top_down <- names(sort(change))[1:15]

mat <- log2cpm[c(top_up, top_down), ]
rownames(mat) <- rowData(airway)[rownames(mat), "gene_name"]
dim(mat)
[1] 30  8

This is a quick ranking, not a statistical test — Post 14 does that properly with DESeq2. But the top of the list already contains the classic glucocorticoid-response genes: FKBP5, TSC22D3, DUSP1 and CRISPLD2.

round(head(mat, 3), 2)
       Ctrl_N61311 Ctrl_N052611 Ctrl_N080611 Ctrl_N061011 Dex_N61311
FKBP5         3.77         4.00         4.68         3.18       7.96
SAMHD1        6.32         6.39         6.05         6.48       9.83
GPX3          5.50         6.97         6.08         6.52       9.71
       Dex_N052611 Dex_N080611 Dex_N061011
FKBP5         8.00        7.49        7.61
SAMHD1       10.34        9.17       10.56
GPX3         10.63        9.05       10.20

FKBP5 rises by about 4 log2 units — roughly 15-fold — in every donor.

round(tail(mat, 3), 2)
          Ctrl_N61311 Ctrl_N052611 Ctrl_N080611 Ctrl_N061011 Dex_N61311
DNM1             6.28         5.66         5.86         6.35       4.54
TMEM35           5.92         5.65         5.46         6.29       4.43
TNFRSF11B        8.46         9.39         9.07         9.25       6.55
          Dex_N052611 Dex_N080611 Dex_N061011
DNM1             3.99        4.01        4.49
TMEM35           4.33        3.16        4.50
TNFRSF11B        7.61        8.19        7.02

Notice what is not in the down-regulated list: IL6, IL1B, TNF and the other inflammatory cytokines you might expect a glucocorticoid to suppress. These cells were never stimulated, so there was little inflammation to switch off. The repressed genes are developmental and extracellular-matrix genes such as SOX4, CXCL12 and ADAMTS14. Real data rarely matches the textbook summary exactly — which is the point of looking.

Stage 1 — The minimal heatmap

One function, one line:

pheatmap(mat)
Default pheatmap of 30 genes by 8 samples on the absolute log2 CPM scale. Samples split into a control and a dex branch, but the gene dendrogram groups CXCL12, GLUL and ADAMTS1 at the top because all three are highly expressed, even though CXCL12 goes down with dex while the other two go up.

Figure 1. pheatmap(mat) with all defaults.

What you get: a heatmap with dendrograms on both axes and gene names on the right. The samples already split into a control branch and a dex branch.

But look at the top three rows. CXCL12 goes down with dex, while GLUL and ADAMTS1 go up — yet they cluster together. They are grouped because all three are highly expressed (deep red everywhere), not because they respond alike. Three things are wrong:

  1. The color scale maps to absolute log2 CPM values. Highly expressed genes dominate the colors and the clustering, hiding the treatment effect.
  2. No group labels. The column names carry the information, but there's no visual cue for treatment or donor.
  3. The default color scale doesn't communicate biology cleanly. Blue-for-below-average and red-for-above-average is the convention in expression data — but only after row-scaling, which we haven't done yet.

What the dendrogram means

Before fixing the aesthetics, it's worth understanding what that tree on the left is actually showing.

Hierarchical clustering treats each gene's expression profile as a point in multi-dimensional space — in our case, eight-dimensional (one dimension per sample). It computes how far apart each pair of genes is, merges the closest two into a cluster, then treats that cluster as a new point and repeats until everything is merged into one tree. The branching structure it builds is the dendrogram. Genes that join at a low branch are similar to each other; genes that only merge near the top are very different.

The distance measure controls what "far apart" means. The default in pheatmap is Euclidean distance — the straight-line distance in 8D space. On unscaled data that is dominated by absolute level, which is exactly why CXCL12 ended up next to GLUL in Figure 1. We'll switch to correlation-based distance in Stage 3, which measures similarity of shape (does the gene go up and down in the same samples?) rather than closeness in absolute value.

The linkage method controls how distances between clusters are computed after the first merge. The default is complete linkage: the distance between two clusters is the maximum pairwise distance between any member of one and any member of the other. Ward.D2 (which we'll use in Stage 3) minimizes total within-cluster variance at each merge step — for expression data, it usually gives tighter, more interpretable groups.

Stage 2 — The publication upgrade

Four changes: colors, scaling, annotation, and annotation colors. We annotate both treatment and donor, because with a paired design you want to see whether samples group by treatment or by the person the cells came from:

annotation_col <- data.frame(
  Treatment = rep(c("Ctrl", "Dex"), each = 4),
  Donor     = rep(c("N61311", "N052611", "N080611", "N061011"), times = 2)
)
rownames(annotation_col) <- colnames(mat)
annotation_col
             Treatment   Donor
Ctrl_N61311       Ctrl  N61311
Ctrl_N052611      Ctrl N052611
Ctrl_N080611      Ctrl N080611
Ctrl_N061011      Ctrl N061011
Dex_N61311         Dex  N61311
Dex_N052611        Dex N052611
Dex_N080611        Dex N080611
Dex_N061011        Dex N061011
ann_colors <- list(
  Treatment = c(Ctrl = "grey80", Dex = "grey25"),
  Donor     = setNames(brewer.pal(4, "Set2"), c("N61311", "N052611", "N080611", "N061011"))
)

pheatmap(mat,
  color             = colorRampPalette(rev(brewer.pal(9, "RdBu")))(100),
  scale             = "row",
  annotation_col    = annotation_col,
  annotation_colors = ann_colors,
  border_color      = NA,
  fontsize_row      = 8,
  fontsize_col      = 9
)
Row-scaled heatmap with a blue-white-red palette and two annotation bars for treatment and donor. Up-regulated genes are blue in the four control samples and red in the four dex samples; down-regulated genes show the opposite.

Figure 2. Row-scaled with an RdBu palette and treatment and donor annotations.

Now each gene is colored relative to its own average, and the pattern jumps out: the 15 induced genes are blue in the controls and red with dex, and the 15 repressed genes are the reverse. The donor bar shows that the samples split by treatment first — within each treatment branch, the donors are mixed.

What each argument does:

  • color = colorRampPalette(rev(brewer.pal(9, "RdBu")))(100) — creates a 100-step palette running from blue (low) through white (middle) to red (high). rev() flips the RdBu palette so blue = low and red = high, matching the convention in most expression papers.
  • scale = "row" — z-scores each row: subtracts the gene's mean across all samples and divides by its SD. After scaling, every gene has mean 0 and SD 1. The color now reflects whether expression is above or below that gene's own average — which is what you actually want to see.
  • annotation_col — a data frame with one row per sample (rownames must match the matrix column names) and one or more columns. Each column becomes a colored annotation bar above the heatmap.
  • annotation_colors — a named list that replaces pheatmap's default (rather loud) annotation colors. Each element is a named vector mapping levels to colors.
  • border_color = NA — removes the grid lines between cells. Optional, but cleaner.
  • fontsize_row = 8, fontsize_col = 9 — adjust font sizes so gene and sample names don't overlap.

Stage 3 — Clustering tuning

Two arguments change the clustering behavior; one adds a visual gap:

pheatmap(mat,
  color                    = colorRampPalette(rev(brewer.pal(9, "RdBu")))(100),
  scale                    = "row",
  annotation_col           = annotation_col,
  annotation_colors        = ann_colors,
  border_color             = NA,
  fontsize_row             = 8,
  fontsize_col             = 9,
  clustering_distance_rows = "correlation",
  clustering_method        = "ward.D2",
  cutree_rows              = 2
)
Final heatmap with correlation distance, Ward.D2 linkage and a gap splitting the genes into two clusters: the 15 dex-induced genes on top and the 15 dex-repressed genes below.

Figure 3. Correlation distance, Ward.D2 linkage and cutree_rows = 2.

The gap now splits the genes into exactly the two groups we selected: all 15 induced genes in one cluster and all 15 repressed genes in the other.

What changed:

  • clustering_distance_rows = "correlation" — switches to Pearson correlation-based distance for the gene dendrogram. Two genes with the same directional response to dex cluster together even if their absolute levels differ. This is almost always a better choice than Euclidean for expression data.
  • clustering_method = "ward.D2" — switches to Ward.D2 linkage, which minimizes within-cluster variance at each merge step. It produces more compact, visually distinct clusters than the default complete linkage.
  • cutree_rows = 2 — cuts the row dendrogram into 2 clusters and draws a gap between them. The number matches the biology: one up-regulated cluster, one down-regulated cluster.

We leave clustering_distance_cols at its default (Euclidean) — with only 8 samples, the choice of distance method matters much less for the column dendrogram.

A heatmap is a display, not evidence

There's a trap here. We picked these 30 genes because they differ between control and dex — so of course the samples cluster by treatment. Clustering on genes you selected by group is circular, and a reviewer will rightly ask about it if you present it as a finding.

To ask honestly whether treatment is the dominant signal, cluster on genes chosen without looking at the groups — for example, the 500 most variable expressed genes:

variance <- apply(log2cpm[expressed, ], 1, var)
top_var  <- names(sort(variance, decreasing = TRUE))[1:500]
cutree(hclust(dist(t(log2cpm[top_var, ]))), k = 2)
 Ctrl_N61311 Ctrl_N052611 Ctrl_N080611 Ctrl_N061011   Dex_N61311  Dex_N052611
           1            1            1            1            2            2
 Dex_N080611  Dex_N061011
           2            2

The samples still split cleanly into controls (cluster 1) and dex (cluster 2), so in this experiment dexamethasone really is the biggest source of variation — larger than the differences between donors. Use the selected-genes heatmap to show the response; use an unbiased check like this (or the PCA plot in Post 14) to support the claim.

The full script

Everything together, copy-paste ready:

library(airway)
library(edgeR)
library(pheatmap)
library(RColorBrewer)

# Data: real airway counts, renamed and ordered Ctrl then Dex
data("airway")
counts  <- assay(airway)
samples <- as.data.frame(colData(airway))[, c("cell", "dex")]
colnames(counts) <- paste0(ifelse(samples$dex == "trt", "Dex", "Ctrl"), "_", samples$cell)
counts  <- counts[, c(1, 3, 5, 7, 2, 4, 6, 8)]
log2cpm <- log2(cpm(counts) + 1)

# Pick the 15 most induced and 15 most repressed expressed genes
expressed <- apply(log2cpm, 1, min) >= 3
change    <- rowMeans(log2cpm[expressed, 5:8] - log2cpm[expressed, 1:4])
top_up    <- names(sort(change, decreasing = TRUE))[1:15]
top_down  <- names(sort(change))[1:15]
mat <- log2cpm[c(top_up, top_down), ]
rownames(mat) <- rowData(airway)[rownames(mat), "gene_name"]

# Annotation
annotation_col <- data.frame(
  Treatment = rep(c("Ctrl", "Dex"), each = 4),
  Donor     = rep(c("N61311", "N052611", "N080611", "N061011"), times = 2)
)
rownames(annotation_col) <- colnames(mat)
ann_colors <- list(
  Treatment = c(Ctrl = "grey80", Dex = "grey25"),
  Donor     = setNames(brewer.pal(4, "Set2"), c("N61311", "N052611", "N080611", "N061011"))
)

# Heatmap
pheatmap(mat,
  color                    = colorRampPalette(rev(brewer.pal(9, "RdBu")))(100),
  scale                    = "row",
  annotation_col           = annotation_col,
  annotation_colors        = ann_colors,
  border_color             = NA,
  fontsize_row             = 8,
  fontsize_col             = 9,
  clustering_distance_rows = "correlation",
  clustering_method        = "ward.D2",
  cutree_rows              = 2
)

The script draws Figure 3. To save it at publication resolution, add filename = "heatmap.png", width = 7, height = 7.5 to the pheatmap() call.

What's next

In the next post, we'll revisit p-values — specifically what happens when you test 30 genes at once. Running a t-test on each gene and reporting the raw p-values is not valid: at p < 0.05, you'd expect 1–2 false positives by chance alone. Post 10 covers multiple testing correction: what p.adjust() is actually doing, when to use FDR versus Bonferroni, and how to apply both in R.


What dataset did you use your first heatmap on? Drop a comment below.

Resources

ResourceLinkNotes
pheatmap packagecran.r-project.org/package=pheatmapKolde R (2019). pheatmap: Pretty Heatmaps. R package version 1.0.12
RColorBrewercran.r-project.org/package=RColorBrewerNeuwirth E (2022). Color palettes including RdBu
pheatmap GitHubgithub.com/raivokolde/pheatmapSource code and full argument reference
airway datasetbioconductor.org/packages/airwayHimes BE et al. (2014). PLoS ONE 9:e99625. doi:10.1371/journal.pone.0099625