Skip to content

Building a DESeq2 Heatmap From Your Own RNA-seq Counts

Oak
A lab instrument holding a glass grid of small squares glowing blue to amber, with a robotic arm shifting two columns.

By the end of this guide you will have two figures and one table. The first figure is a sample-distance heatmap that tells you whether your samples cluster the way your metadata says they should. The second is a gene-level heatmap of differentially expressed genes with variance-stabilized, row-centered values and a symmetric color scale. The table is the ordered gene list behind the figure, with cluster assignments, so the picture is reproducible rather than decorative. You need the following.

  • R 4.3 or newer
  • the Bioconductor packages DESeq2, tximport and pheatmap, with limma and matrixStats
  • a quant.sf file per sample from Salmon (or a counts matrix from featureCounts)
  • a transcript-to-gene map
  • a sample table with at least one condition column

Everything below assumes gene-level counts and at least three samples per group you intend to compare.

1. Load counts and build the DESeqDataSet

The heatmap inherits every decision you make at import, so start there. If you quantified with Salmon, import at the transcript level and summarize to genes with tximport. This carries the effective transcript lengths into DESeq2 as an offset, which corrects for changes in isoform usage that would otherwise look like changes in gene expression.

library(DESeq2); library(tximport); library(readr)

samples <- read_csv("samples.csv")          # id, condition, batch, timepoint
files <- file.path("quants", samples$id, "quant.sf")
names(files) <- samples$id
stopifnot(all(file.exists(files)))

txi <- tximport(files, type = "salmon", tx2gene = tx2gene,
                countsFromAbundance = "no")

samples$condition <- factor(samples$condition, levels = c("baseline", "treatment"))
samples$batch     <- factor(samples$batch)

dds <- DESeqDataSetFromTximport(txi, colData = samples,
                                design = ~ batch + condition)

Put the variable of interest last in the design formula. DESeq2 builds the default results contrast from the last term, and nuisance variables such as sequencing batch or RIN bin belong earlier. If you are working with repeated samples from one person over time, the analogous design is ~ timepoint with a likelihood ratio test, and your “replicates” are separate blood draws rather than separate people. That changes the interpretation and not the mechanics: you are measuring within-person variation across time.

Filter low-count genes before fitting. This is for speed and for the independent filtering step, and it also keeps noisy near-zero rows out of the variance ranking you will use later.

smallestGroup <- min(table(samples$condition))
keep <- rowSums(counts(dds) >= 10) >= smallestGroup
dds <- dds[keep, ]
dds <- DESeq(dds)
res <- results(dds, contrast = c("condition", "treatment", "baseline"), alpha = 0.05)
summary(res)

2. Transform the counts for visualization

Raw and normalized counts are the wrong input for a heatmap. Counts are heteroskedastic: high-expression genes have large absolute variance simply because they are large. Clustering on them ranks genes by mean expression instead of by pattern. DESeq2 supplies two transforms that flatten the mean-variance relationship.

vsd <- vst(dds, blind = FALSE)     # fast, use for n >= ~20
rld <- rlog(dds, blind = FALSE)    # shrinks harder at low counts, slow above ~30 samples

We use vst by default and switch to rlog when there are fewer than about twenty samples or when library sizes differ by more than roughly fourfold. The blind argument controls whether the dispersion trend is estimated with the design in place. Use blind = TRUE for pure quality control, before you trust your metadata. Use blind = FALSE once you are visualizing a result, because blind estimation treats real condition-driven differences as noise and over-shrinks exactly the signal you want to see. Neither transform changes the differential expression test. They exist for the geometric steps: distances, clustering, and principal components.

3. Check sample distances before you look at genes

Draw the sample-distance heatmap first. It is the cheapest way to catch a swapped label or a failed library, and it costs four lines.

library(pheatmap); library(RColorBrewer)

sampleDists <- dist(t(assay(vsd)))
mat <- as.matrix(sampleDists)
rownames(mat) <- paste(vsd$condition, vsd$id, sep = " | ")
colnames(mat) <- NULL

pheatmap(mat,
         clustering_distance_rows = sampleDists,
         clustering_distance_cols = sampleDists,
         col = colorRampPalette(rev(brewer.pal(9, "Blues")))(255))

If samples cluster by batch rather than by condition, stop and fix the model before making the gene heatmap. If one sample sits alone at the far edge of the dendrogram, check its mapping rate and its duplication rate before deciding it is biology. In multi-omics work this step matters more, because a mislabeled sample propagates into every downstream layer you join against the transcriptome.1

4. Choose which genes go into the heatmap

This is where most heatmaps go wrong. There are two defensible selections and they answer different questions.

The first is the top-variance selection. It is unsupervised and makes no reference to your test.

library(matrixStats)
topVar <- head(order(rowVars(assay(vsd)), decreasing = TRUE), 500)

The second is the significance selection, which is what you want if the figure is meant to illustrate a differential expression result.

sig <- subset(as.data.frame(res), padj < 0.05 & abs(log2FoldChange) > 1)
sig <- sig[order(sig$padj), ]
sel <- head(rownames(sig), 100)

Be explicit in the caption about which you used. A heatmap of genes chosen because they separate the groups will show groups separating. That is circular if you present it as evidence that the groups differ. The top-variance version avoids the circularity but will be dominated by whatever the largest source of variation is, which is often batch or sex. We generally plot the significance selection and say so plainly, then keep the variance selection as an internal check on whether the design captured the dominant structure.

Cap the number of rows at what the page can render. Above roughly 80 genes the row labels stop being readable, and at that point the figure communicates block structure rather than individual genes. If you want both, plot 500 genes without row labels and annotate a handful with ComplexHeatmap::anno_mark.

5. Center the rows and set a symmetric color scale

A heatmap of untransformed VST values shows expression level. A heatmap of row-centered values shows pattern across samples. Almost always you want pattern, because a ribosomal gene at VST 14 and a transcription factor at VST 6 cannot share a useful color scale.

m <- assay(vsd)[sel, ]
m <- m - rowMeans(m)                     # center; units stay log2-like
# m <- m / rowSds(m)                     # optional z-scoring

We center but do not divide by the row standard deviation by default. Centering alone keeps the color scale in log2 units, so a value of +1 means twofold above that gene’s mean across your samples. Z-scoring makes every gene look equally variable, which flatters weak genes and hides effect size. Use z-scoring only when the point of the figure is co-expression shape rather than magnitude.

Set the breaks by hand. pheatmap defaults to a scale spanning the full data range, so a single extreme gene can wash out everything else. Clip at a high quantile and force the palette midpoint to zero.

lim <- as.numeric(quantile(abs(m), 0.98))
breaks <- seq(-lim, lim, length.out = 101)
pal <- colorRampPalette(c("#2166AC", "#F7F7F7", "#B2182B"))(100)

Use a diverging palette with a neutral middle for centered data, and a sequential palette only for uncentered data. Blue-white-red is conventional for expression. If colorblind accessibility matters, RColorBrewer::brewer.pal(11, "PuOr") reads more reliably than red-green.

6. Draw the heatmap

ann_col <- as.data.frame(colData(vsd)[, c("condition", "batch")])
ann_colors <- list(
  condition = c(baseline = "#4D4D4D", treatment = "#E08214"),
  batch     = c(`1` = "#FFFFFF", `2` = "#BDBDBD")
)

pheatmap(m,
         color = pal,
         breaks = breaks,
         scale = "none",
         cluster_rows = TRUE,
         cluster_cols = TRUE,
         clustering_distance_rows = "correlation",
         clustering_distance_cols = "euclidean",
         clustering_method = "ward.D2",
         annotation_col = ann_col,
         annotation_colors = ann_colors,
         show_rownames = TRUE,
         fontsize_row = 7,
         border_color = NA,
         treeheight_row = 25,
         filename = "figures/deg_heatmap.pdf",
         width = 6.5, height = 9)

Two arguments deserve comment. Setting scale = "none" is mandatory once you have centered the matrix yourself, otherwise pheatmap z-scores it again and your carefully chosen breaks no longer mean anything. Choosing clustering_distance_rows = "correlation" groups genes by shape rather than amplitude, which is what you want for co-expression blocks. Euclidean distance on columns keeps sample clustering consistent with the distance heatmap from step 3. We prefer ward.D2 linkage because it produces compact, roughly equal-sized clusters, where average linkage tends to chain and leave one giant cluster.

If you want the rows in a fixed biological order rather than a dendrogram order, set cluster_rows = FALSE and order m yourself, for example by log2 fold change sign and then by adjusted p-value.

7. Remove nuisance effects for the figure only

If batch dominates the picture and batch is already in your design, you can subtract its fitted contribution before plotting. The differential expression test already accounted for it. The heatmap has not.

mat <- assay(vsd)
design0 <- model.matrix(~ condition, colData(vsd))
assay(vsd) <- limma::removeBatchEffect(mat, batch = vsd$batch, design = design0)

This is a visualization step. Never run the DESeq2 test on batch-corrected values, and never report the corrected matrix as data. Passing design0 protects the condition effect from being absorbed into the batch correction. If batch and condition are fully confounded, removeBatchEffect will silently remove the biology too, and no plotting choice can recover it.

8. Export the gene list behind the figure

The figure is a summary. The table is the result. Cut the row dendrogram into clusters and write out everything a reader would need to rebuild the plot.

ph <- pheatmap(m, silent = TRUE, clustering_distance_rows = "correlation",
               clustering_method = "ward.D2")
clusters <- cutree(ph$tree_row, k = 4)

out <- data.frame(
  gene       = rownames(m),
  cluster    = clusters[rownames(m)],
  baseMean   = res[rownames(m), "baseMean"],
  log2FC     = res[rownames(m), "log2FoldChange"],
  padj       = res[rownames(m), "padj"]
)
write.csv(out[order(out$cluster, out$padj), ], "results/heatmap_genes.csv", row.names = FALSE)

Cluster assignments are the natural handoff point to enrichment analysis and to other data layers. Published multi-omics work follows the same pattern: transcriptomic clusters are defined first, then intersected with proteomic or metabolomic signals to find features that move together across layers.23 The same join works on personal data, where a transcript cluster can be lined up against plasma protein measurements and repeated blood biomarker panels from the same draws.4

One boundary is worth stating directly. A heatmap shows patterns in your measurements and nothing else. It does not establish that a gene is causing anything, and it says nothing about what any individual should do. Any move from a figure to a health decision requires a clinician who can see the full clinical picture.

Common problems

Clustering ranks genes by expression level instead of pattern. You plotted counts(dds, normalized = TRUE) or a plain log2 of counts. Use vst or rlog output and center the rows.

Every row is the same shade of red or blue. Your color breaks are not symmetric around zero, usually because you centered the matrix but left pheatmap to pick the scale. Pass explicit breaks spanning -lim to +lim.

Rows disappear or hclust throws an error about missing values. Some row has zero variance, which makes the correlation distance undefined. Drop them with m <- m[rowSds(m) > 0, ] before clustering. Constant rows usually survive filtering when a gene has the same small count in every sample.

Samples cluster by batch. Confirm that batch is in the design, then apply removeBatchEffect for the figure. If the dendrogram still splits on batch afterward, the batch effect is not additive on the VST scale, and the move is to report it rather than plot around it.

The heatmap looks convincing but the p-values are weak. Check whether you selected genes by significance and then presented the separation as independent evidence. Also check group sizes. With three versus three, a clean two-block heatmap of the top 50 genes by adjusted p-value is close to guaranteed, even under the null.

Gene identifiers are unreadable Ensembl IDs. Map them once, before plotting, and keep both columns. Use AnnotationDbi::mapIds(org.Hs.eg.db, rownames(m), "SYMBOL", "ENSEMBL") and fall back to the Ensembl ID when the symbol is NA, otherwise you will silently lose rows.

Two runs of the same script produce different dendrograms. Ties in the distance matrix break differently depending on row order. Sort the matrix deterministically before clustering and set set.seed() if any step samples.

Row centering hides a global shift. If all samples in one condition are shifted up, centering removes that shift and the figure looks flat. Verify with the uncentered matrix and with the size factors from sizeFactors(dds). A genuine global change in RNA content breaks the median-of-ratios normalization assumption, and spike-ins are the only clean way to detect it.

Interpretation drifts from the transcript to the protein. Messenger RNA levels and protein levels correlate imperfectly, and multi-omics studies repeatedly find transcript changes without matching protein changes in the same tissue.15 Treat a transcriptomic cluster as a hypothesis about the proteome. It is not a measurement of the proteome.

Footnotes

  1. Mattias Backman, Florian Flenkenthaler, Andreas Blutke, et al. Multi-Omics Insights into Functional Alterations of the Liver in Insulin-Deficient Diabetes Mellitus. SSRN Electronic Journal, 2018. https://doi.org/10.2139/ssrn.3307901 ↩ ↩2

  2. Joseph Pierre Aboumsallem, Canxia Shi, Sanne De Wit, et al. Multi-omics analyses identify molecular signatures with prognostic values in different heart failure aetiologies. Journal of Molecular and Cellular Cardiology, 2023. https://doi.org/10.1016/j.yjmcc.2022.12.001 ↩

  3. Jie Chen, Tingting Zhao, Hongfei Li, et al. Multi-Omics Analysis of Gut Microbiota and Host Transcriptomics Reveal Dysregulated Immune Response and Metabolism in Young Adults with Irritable Bowel Syndrome. International Journal of Molecular Sciences, 2024. https://doi.org/10.3390/ijms25063514 ↩

  4. Marta Ballanti, Lorenzo Antonetti, Maria Mavilio, et al. Decreased circulating IPA levels identify subjects with metabolic comorbidities: A multi-omics study. Pharmacological Research, 2024. https://doi.org/10.1016/j.phrs.2024.107207 ↩

  5. Esraa M Hashem, Mai S. Mabrouk. Multi-omics integration uncovers epigenetic control of metabolic reprogramming in triple-negative breast cancer. Journal of the Egyptian National Cancer Institute, 2026. https://doi.org/10.1186/s43046-026-00401-7 ↩

Pothos builds longitudinal molecular profiles of individuals: whole-genome sequencing, single-cell RNA sequencing, and plasma proteomics, delivered as a detailed report, every data file, and stored cells. Build your profile.