How to Make a Heatmap of Differentially Expressed Genes in R
By the end of this guide you will have a publication-quality heatmap of differentially expressed genes. Rows are genes and columns are samples, and colors are row-wise z-scores of variance-stabilized counts. The sample annotations sit above the matrix as colored bars. You need R 4.3 or later, a gene-by-sample matrix of raw integer counts (from featureCounts, HTSeq, or tximport on Salmon quantifications), and a sample metadata table with at least one column describing the contrast you care about. Install DESeq2, ComplexHeatmap, and circlize from Bioconductor. Then install matrixStats and apeglm. We use ComplexHeatmap rather than pheatmap throughout. It gives you control over row splitting, multiple annotation tracks, and the color mapping function. It also has defaults that are less likely to mislead you. Everything below assumes bulk RNA-seq. Single-cell heatmaps need a different normalization path.
1. Load counts and metadata, and check they agree
The first step is boring and is where most heatmaps go wrong. Your counts matrix and your metadata must be aligned by sample, in the same order, with identical identifiers. DESeq2 will refuse to build an object if the names mismatch, but it will happily accept a silently reordered metadata table if you strip the names first.
library(DESeq2)
library(ComplexHeatmap)
library(circlize)
library(matrixStats)
counts <- as.matrix(read.csv("counts.csv", row.names = 1))
meta <- read.csv("samples.csv", row.names = 1, stringsAsFactors = TRUE)
stopifnot(all(colnames(counts) == rownames(meta)))
storage.mode(counts) <- "integer"
If the stopifnot fails, fix it by subsetting rather than sorting both. Write meta <- meta[colnames(counts), , drop = FALSE] and then re-run the check. Drop genes with essentially no signal before you do anything else. A common filter is keeping genes with at least 10 counts in at least as many samples as your smallest group.
smallest_group <- min(table(meta$condition))
keep <- rowSums(counts >= 10) >= smallest_group
counts <- counts[keep, ]
On a human dataset this typically takes you from roughly 60,000 annotated features to 14,000 to 18,000 expressed genes. The filter speeds up the fit and improves the multiple-testing correction, since you are no longer testing thousands of genes that carry no information.
2. Run the differential test
The heatmap is a display of a result, so you need the result first. Build the DESeq2 object with an explicit design and an explicit reference level, because R will otherwise pick the alphabetically first factor level and your log fold changes will point the wrong way.
meta$condition <- relevel(meta$condition, ref = "control")
dds <- DESeqDataSetFromMatrix(counts, colData = meta,
design = ~ batch + condition)
dds <- DESeq(dds)
res <- results(dds, contrast = c("condition", "treated", "control"),
alpha = 0.05)
res <- lfcShrink(dds, coef = "condition_treated_vs_control",
type = "apeglm", res = res)
Include batch in the design if you have one. Shrinkage with apeglm changes the log fold change estimates without changing the p-values, and it stops low-count genes with wild ratios from dominating any fold-change-based gene selection. If you are analyzing a longitudinal profile of one person rather than two groups of people, replace ~ condition with a design over timepoint or state, and be aware that with a single subject you have no biological replication across individuals. Your inference then describes that person over time and does not generalize.
Published RNA-seq analyses commonly combine this kind of differential test with pathway enrichment on the resulting gene list, and the heatmap is the figure that sits between the two 1.
3. Transform the counts for display
Never plot raw counts or raw CPM on a heatmap. Count data is heteroscedastic: high-expression genes have much larger absolute variance than low-expression genes, so a Euclidean-distance clustering on untransformed counts is dominated by a handful of ribosomal and mitochondrial transcripts. Use the variance-stabilizing transformation.
vsd <- vst(dds, blind = FALSE)
mat_all <- assay(vsd)
Use blind = FALSE here. Blind transformation refits dispersion with an intercept-only design, which is the right choice for quality control but is unnecessarily conservative once you have decided on a model. For fewer than about 30 samples rlog(dds, blind = FALSE) is a reasonable alternative and is somewhat better behaved when library sizes vary by more than tenfold. It is much slower, so on anything above 50 samples use vst.
If your design includes a nuisance factor, remove it from the display matrix only.
library(limma)
mat_all <- removeBatchEffect(mat_all,
batch = vsd$batch,
design = model.matrix(~ condition, colData(vsd)))
This is a cosmetic correction for the figure. The statistics already accounted for batch inside the model. Do not feed a batch-corrected matrix back into DESeq2.
4. Choose the genes
Two selection rules cover almost every case, and they answer different questions.
The first is a significance-and-effect filter. Take genes with an adjusted p-value below 0.05 and a shrunken absolute log2 fold change above 1, which is a doubling or halving.
sig <- subset(as.data.frame(res),
padj < 0.05 & abs(log2FoldChange) > 1)
sig <- sig[order(sig$padj), ]
genes <- head(rownames(sig), 50)
Fifty rows is about the limit for readable gene labels at a standard figure width. Above roughly 80 rows, turn labels off and treat the heatmap as a texture rather than a lookup table.
The second rule is unsupervised: take the top 500 or 1,000 genes by row variance across all samples, with no reference to the contrast.
rv <- rowVars(mat_all)
genes_unsup <- rownames(mat_all)[order(rv, decreasing = TRUE)][1:1000]
Here is the tradeoff that most tutorials skip. If you select genes because they differ between your groups and then cluster the samples using only those genes, the samples will separate cleanly by group. That separation is a consequence of the selection and carries no evidence. The unsupervised variance-ranked heatmap is the one that can tell you something you did not already assume, including that your dominant source of variation is a batch or a sex effect rather than your treatment. We make both figures every time and read the unsupervised one first.
5. Scale rows and pin the color mapping
Subset the transformed matrix to your chosen genes and convert each row to a z-score. Scaling per row is what makes a low-expression gene and a high-expression gene comparable in the same panel.
mat <- mat_all[genes, ]
mat_z <- t(scale(t(mat)))
mat_z[is.na(mat_z)] <- 0
The is.na line handles rows with zero variance after filtering, which would otherwise divide by zero and produce blank stripes.
Now fix the color scale explicitly rather than letting the package infer it from the data range. An inferred scale makes two figures from the same experiment incomparable, and a single outlier sample can wash out the entire panel.
col_fun <- colorRamp2(c(-2, 0, 2),
c("#2166AC", "#FFFFFF", "#B2182B"))
Values beyond ±2 saturate at the endpoint colors, which is what you want. This blue-white-red ramp is from ColorBrewer’s RdBu and is close to a diverging perceptual scale. Do not use a red-green ramp. Roughly 8% of men of northern European ancestry have some form of red-green color vision deficiency and will not be able to read the figure. If you need to show absolute expression rather than z-scores, switch to a sequential viridis ramp and drop the diverging midpoint.
6. Cluster rows and columns deliberately
Clustering defaults matter more than people expect. hclust defaults to complete linkage on Euclidean distance, which produces compact but often arbitrary row groups.
For rows of z-scored data we prefer correlation distance, because two genes with the same shape across samples should cluster together regardless of amplitude. For columns, Euclidean distance on the same scaled matrix is reasonable. Ward linkage gives more balanced and interpretable sample groupings.
row_dist <- function(m) as.dist(1 - cor(t(m), method = "pearson"))
col_dist <- function(m) dist(m, method = "euclidean")
ht <- Heatmap(mat_z,
name = "z-score",
col = col_fun,
clustering_distance_rows = row_dist,
clustering_method_rows = "ward.D2",
clustering_distance_columns = col_dist,
clustering_method_columns = "ward.D2",
row_split = 3,
show_row_names = TRUE,
row_names_gp = gpar(fontsize = 7),
column_names_gp = gpar(fontsize = 9))
row_split = 3 cuts the row dendrogram into three blocks, which is usually enough to separate up-regulated from down-regulated genes and to isolate a third group with a mixed pattern. If you instead pass row_km = 3, ComplexHeatmap runs k-means, which is stochastic. Call set.seed(42) first or your figure will change between runs.
Consider turning off column clustering when the column order carries meaning. For a time course, cluster_columns = FALSE with samples ordered by timepoint is far more readable than a dendrogram that scrambles the axis.
7. Add annotations
Annotation tracks are what turn a colored grid into an interpretable figure. They let a reader check whether the sample clusters line up with the biological variable or with something else.
ha <- HeatmapAnnotation(
condition = vsd$condition,
batch = vsd$batch,
col = list(
condition = c(control = "#4DAF4A", treated = "#984EA3"),
batch = c(`1` = "#BBBBBB", `2` = "#444444")
),
annotation_name_gp = gpar(fontsize = 8)
)
lfc <- res[genes, "log2FoldChange"]
ra <- rowAnnotation(
log2FC = anno_barplot(lfc, gp = gpar(fill = "#666666")),
width = unit(2, "cm")
)
ht <- Heatmap(mat_z, name = "z-score", col = col_fun,
top_annotation = ha, right_annotation = ra,
clustering_distance_rows = row_dist,
clustering_method_rows = "ward.D2",
row_split = 3,
row_names_gp = gpar(fontsize = 7))
Always specify annotation colors by hand. Automatic palettes reuse hues across tracks and invite misreading. The log2FC barplot on the right is worth the space: it shows effect size next to a panel that otherwise only shows relative pattern.
Several R packages wrap this annotated-heatmap pattern together with enrichment and multi-omic overlays, including TOmicsVis for transcriptomic workflows 2 and MultiModalGraphics for figures that combine expression with a second assay 3. For interactive exploration across several omics layers at once, a Shiny front end such as xOmicsShiny lets you re-cluster and re-select genes without rewriting code 4. We still recommend writing the ComplexHeatmap call yourself for the final figure, because you can see and version every parameter.
8. Render and save
Draw the object, then write it to a vector format at a fixed physical size.
pdf("deg_heatmap.pdf", width = 7, height = 9)
draw(ht, heatmap_legend_side = "right",
annotation_legend_side = "right",
merge_legend = TRUE)
dev.off()
Use PDF or SVG so labels stay sharp. If a journal demands raster, use png(..., width = 7, height = 9, units = "in", res = 600). For matrices above about 5,000 rows, add use_raster = TRUE, raster_quality = 4 to the Heatmap call. That rasterizes the cell body while keeping text and dendrograms as vectors.
Save the inputs alongside the figure. Write out mat_z, the gene list, and sessionInfo(). Six months later you will want to know which DESeq2 version produced a specific block of rows.
9. Take the gene clusters somewhere
A heatmap ends with a question: what are these row blocks. Pull the cluster memberships out of the drawn object and pass them to enrichment.
ht_drawn <- draw(ht)
clusters <- row_order(ht_drawn)
cluster_genes <- lapply(clusters, function(i) rownames(mat_z)[i])
Each element of cluster_genes is a coherent set of co-varying genes and is a better enrichment input than the full differential list, because the blocks separate opposing directions of change. Tools such as pathfindR test these lists against pathway databases while accounting for protein-protein interaction structure, which tends to surface more specific terms than a plain over-representation test 5. If your figure needs a genomic rather than a pathway view, ChromoMap will place the same gene set along chromosome ideograms 6.
Common problems
The heatmap is one solid color. Your color mapping is being stretched by an extreme value. Check range(mat_z) and confirm you passed the col_fun object rather than a vector of colors. Also check for a sample with a failed library, which produces an entire column of extreme z-scores.
Rows appear in a different order every time. You used row_km without a seed. Either set one or switch to row_split on the dendrogram, which is deterministic.
The clustering separates by batch instead of condition. This is real information. It is not a bug. Confirm it on the unsupervised variance-ranked heatmap. If the batch effect dominates there, keep batch in the DESeq2 design and use removeBatchEffect for the display matrix only.
All genes look up-regulated. You scaled columns instead of rows. scale() in R operates on columns, so the transpose sandwich t(scale(t(mat))) is required. Verify with rowMeans(mat_z), which should be effectively zero.
Gene labels are unreadable. Set show_row_names = FALSE and add a rowAnnotation with anno_mark() to label only the 15 or 20 genes you want to name.
Every gene is significant. With large sample sizes, tiny fold changes clear a padj threshold. Tighten the effect size filter to abs(log2FoldChange) > 1 and report both cutoffs in the caption.
You mapped Ensembl IDs to symbols and lost rows. Mapping is many-to-one and some IDs have no symbol. Keep the Ensembl ID as the row name internally and attach symbols only at the labeling step, so a failed mapping degrades to an ID rather than dropping a gene.
Reading a heatmap tells you about patterns of relative expression across samples. It does not tell you what any pattern means for a person’s health, and no figure produced this way is a clinical result. If something in your own data prompts a health question, take it to a clinician.
Footnotes
-
A. Siavoshi, M. Taghizadeh, E. Dookhe, et al. Gene expression profiles and pathway enrichment analysis to identification of differentially expressed gene and signaling pathways in epithelial ovarian cancer based on high-throughput RNA-seq data. Genomics, 2022. https://doi.org/10.1016/j.ygeno.2021.11.031 ↩
-
Ben‐Ben Miao, Wei Dong, Zhao‐Fang Han, et al. TOmicsVis: An all‐in‐one transcriptomic analysis and visualization R package with Shinyapp interface. iMeta, 2023. https://doi.org/10.1002/imt2.137 ↩
-
Foziya Ahmed Mohammed, El Hadj Malick Fall, Kula Kekeba Tune, et al. MultiModalGraphics: an R package for graphical integration of multi-omics datasets. BMC Bioinformatics, 2025. https://doi.org/10.1186/s12859-025-06265-3 ↩
-
Benbo Gao, Yu H Sun, Xinmin Zhang, et al. xOmicsShiny: an R Shiny application for cross-omics data analysis and pathway mapping. Bioinformatics Advances, 2024. https://doi.org/10.1093/bioadv/vbaf097 ↩
-
Ege Ulgen, Ozan Ozisik, Osman Ugur Sezerman. pathfindR: An R Package for Comprehensive Identification of Enriched Pathways in Omics Data Through Active Subnetworks. Frontiers in Genetics, 2019. https://doi.org/10.3389/fgene.2019.00858 ↩
-
Lakshay Anand, Carlos M. Rodriguez Lopez. ChromoMap: an R package for interactive visualization of multi-omics data and annotation of chromosomes. BMC Bioinformatics, 2022. https://doi.org/10.1186/s12859-021-04556-z ↩
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.