Heatmaps and Clustering That Mean Something

A good heatmap shows the structure in your experiment at a glance: which samples belong together, and which genes drive the difference between groups. But only if you prepare the data the right way first. Let's do it properly in R.

🟡 Intermediate ⏱️ ~1 hour 📊 R 🌐 Runs free in Colab

Before you start

Learning objectives

By the end of this lesson you will be able to: build a heatmap of expression in R, understand how clustering groups genes and samples, and choose scaling and gene selection so the figure shows real structure rather than noise.

First rule: never heatmap raw counts

It's tempting to throw your count matrix straight into a heatmap, but it will mislead you. Raw counts span an enormous range (some genes have tens of reads, others tens of thousands), and they depend on how deeply each sample was sequenced. A heatmap of raw counts just shows you a handful of very high-count genes and hides everything else.

The fix is a variance-stabilizing transformation. It corrects for sequencing depth and makes a gene's spread roughly independent of its average level, so noisy low-count genes and a few very high-count genes stop dominating distances and clustering. (Later, z-scoring each gene puts every gene on the same footing for the colours.) DESeq2 gives you one in a single line.

Decode the jargonVariance-stabilizing transformation (vst)

A transformation that flattens the relationship between a gene's average count and its variability, so highly expressed genes stop dominating. The result is values you can safely cluster, plot, and compare across samples. DESeq2's vst() is fast and works well for real datasets (it needs at least 1,000 genes); varianceStabilizingTransformation() does the same job on any size, and rlog() is a gentler alternative when you have few samples.

▶ Code along in Google Colab

Set the runtime to R (Runtime, then Change runtime type, then R), and run each block as you read. The DESeq2 install takes about 3 to 5 minutes the first time, which is completely normal and only happens once per session.

Open the R notebook in Colab →

1Set up and transform

Rebuild the dataset from the previous lessons, then transform it. We'll also install pheatmap, a small, friendly package for drawing heatmaps.

library(DESeq2)
install.packages("pheatmap")   # small CRAN package, installs quickly
library(pheatmap)

base <- "https://raw.githubusercontent.com/MennahBassiouny/bionexus/main/"

# Count matrix: rows = genes (Ensembl IDs), columns = the 8 samples
counts  <- as.matrix(read.csv(paste0(base, "airway-counts.csv"), row.names = 1))
# Sample table: which donor (cell) and whether it was treated (dex)
samples <- read.csv(paste0(base, "airway-samples.csv"), row.names = 1)
# Gene names, so results show DUSP1 instead of ENSG00000120129
genes   <- read.csv(paste0(base, "airway-genes.csv"), row.names = 1)

samples$cell <- factor(samples$cell)
samples$dex  <- factor(samples$dex, levels = c("untrt", "trt"))  # untreated = baseline
samples <- samples[colnames(counts), ]   # same order as the count columns

dds <- DESeqDataSetFromMatrix(counts, samples, design = ~ cell + dex)
dds <- DESeq(dds)
res <- results(dds, contrast = c("dex", "trt", "untrt"), alpha = 0.05)

# the transformed values we'll use for every plot below
vsd <- vst(dds, blind = FALSE)

2Do my samples cluster by treatment? (the QC heatmap)

Before trusting any result, ask a basic question: do replicates of the same condition look alike? We answer it by measuring the distance between every pair of samples and drawing those distances as a heatmap.

sampleDists <- dist(t(assay(vsd)))   # distance between samples
mat <- as.matrix(sampleDists)
ann <- as.data.frame(colData(vsd)[, c("dex", "cell")])   # colour bars: treatment and donor

pheatmap(mat,
         clustering_distance_rows = sampleDists,
         clustering_distance_cols = sampleDists,
         annotation_col = ann,
         main = "Sample-to-sample distances")

How to read it: in pheatmap's default colours, blue (cool) means a small distance, so the two samples are more similar, and red (warm) means they are less similar. You want samples of the same condition to sit together in tight blocks, with a clear split between groups. In airway, the four untreated samples form one block and the four treated samples another. If one sample clusters with the wrong group, that's a red flag worth investigating: a possible sample swap, a batch effect, or an outlier. This single plot catches problems that would otherwise quietly ruin your conclusions.

3The same question, even faster: PCA

A PCA plot squeezes all the genes down to two axes that capture the biggest sources of variation, so you can see the grouping in one glance. DESeq2 has it built in.

plotPCA(vsd, intgroup = c("dex", "cell"))

In airway, the untreated and treated samples separate along the first axis (PC1, about 48% of the variation), and the second axis (PC2, about 23%) mostly reflects which donor the cells came from. That is a healthy picture: the treatment is the biggest signal, and the donor effect is real but smaller, which is exactly why the design includes cell.

4Which genes separate the groups? (the gene heatmap)

Now the satisfying one. We take the most differentially expressed genes, scale each gene so we see its pattern rather than its absolute level, and let clustering arrange them.

# the 30 most significant genes (padj < 0.05)
sig <- which(!is.na(res$padj) & res$padj < 0.05)
top <- head(sig[order(res$padj[sig])], 30)
mat <- assay(vsd)[top, ]

# z-score each gene across samples (centre and scale per row)
mat <- t(scale(t(mat)))
rownames(mat) <- genes[rownames(mat), "symbol"]   # show gene names

pheatmap(mat,
         annotation_col = ann,   # treatment and donor bars, from above
         main = "Top 30 genes (z-scored)")

Read it as blocks of colour. A clean result shows two opposing blocks: a set of genes high (red) in the untreated samples and low (blue) after treatment, and another set doing the reverse. The gene names on the right include steroid-response genes such as DUSP1, KLF15 and PER1. The samples will usually group by condition here. That is expected, because we picked genes that differ between the conditions, so it is not independent proof that the hits are real. For an unbiased check, use the sample-distance heatmap above and a PCA, which use all genes.

Decode the jargonZ-score scaling

For each gene, we subtract its mean and divide by its standard deviation across samples. This rescales every gene to the same footing so the heatmap shows relative change (up or down versus that gene's own average) instead of which genes are simply loud. Without it, a few high-expression genes would wash out the pattern you care about.

🔶 Level up: prettier and bigger heatmaps

pheatmap has many options worth exploring: custom colour palettes, splitting rows or columns into groups with cutree_rows, and adding multiple annotation tracks. For complex, publication-grade figures, the ComplexHeatmap Bioconductor package is the community standard once you outgrow the basics.

Check your understanding

Why transform the counts with vst before making a heatmap?
Raw counts span a huge range and depend on sequencing depth, so a few high-count genes would dominate the colours. The variance-stabilizing transform corrects for depth and makes each gene's spread roughly independent of its average level, so real patterns drive distances and clustering instead of raw magnitude.
What does the sample-distance heatmap tell you?
Whether replicates of the same condition are actually similar to each other. Tight same-condition blocks with a clean split between groups is healthy. A sample sitting with the wrong group hints at a swap, a batch effect, or an outlier.
Why z-score each gene before the gene heatmap?
So the heatmap shows each gene's relative change (up or down versus its own average) rather than its absolute expression level. Otherwise a handful of very highly expressed genes would dominate and hide the pattern.
After z-scoring a gene, what does a value of 0 mean for one sample?
A z-score of 0 means that sample sits exactly at the gene's mean. Positive values are above average (higher than usual) and negative values are below, which is why heatmap colours read as relative up or down.
What does hierarchical clustering do to the rows and columns of a gene heatmap?
Clustering groups genes with similar expression patterns together and samples that look alike together, so blocks of co-regulated genes and related samples become visible as clear patches of colour.

Sources & further reading

  1. Love MI, Huber W, Anders S. Moderated estimation of fold change and dispersion for RNA-seq data with DESeq2. Genome Biology 15: 550, 2014. (variance-stabilizing transformation, sample distances) doi:10.1186/s13059-014-0550-8
  2. Conesa A, Madrigal P, Tarazona S, et al. A survey of best practices for RNA-seq data analysis. Genome Biology 17: 13, 2016. doi:10.1186/s13059-016-0881-8
  3. Gu Z, Eils R, Schlesner M. Complex heatmaps reveal patterns and correlations in multidimensional genomic data. Bioinformatics 32: 2847-2849, 2016. (ComplexHeatmap) doi:10.1093/bioinformatics/btw313
  4. Himes BE, Jiang X, Wagner P, et al. RNA-Seq transcriptome profiling identifies CRISPLD2 as a glucocorticoid responsive gene that modulates cytokine function in airway smooth muscle cells. PLoS One 9: e99625, 2014. (The airway dataset used in this lesson.) doi:10.1371/journal.pone.0099625

Last reviewed: October 2026.

Next in Track 3

Functional enrichment: GO, KEGG, GSEA →