BioMatikaBioMatika
← BlogMethods

How to create publication-ready heatmaps in R from raw gene expression data

Heatmaps represent the magnitude or the density of data values using colour gradients.

Dr. Gabija Vaitkevičiūtė
Dec 2026 · 5 min read
Clustered heatmap of the top 20 differentially expressed genes in four human airway smooth muscle cell lines, untreated and treated with dexamethasone
Figure 1. Heatmap of top 20 differentially expressed genes in four human airway smooth muscle cell lines untreated treated with dexamethasone.

Heatmaps represent the magnitude or the density of data values using colour gradients. The rows and columns represent categories — this method helps clarify patterns and trends in data. Heatmaps are often used to visualise gene expression, metabolite concentrations or protein abundance.

In this guide, we will walk through how to process raw transcriptomic data, map Ensembl IDs to readable gene symbols, compute variance-stabilised matrix values, and construct an annotated, publication-ready heatmap using pheatmap.

1. What are heatmaps and why should researchers use them?

When working with multi-sample high-throughput experiments (such as RNA-seq or proteomics), inspecting raw tables of thousands of variables is impractical. Heatmaps solve this by converting numerical matrices into intuitive visual maps.

Key features of an effective expression heatmap include:

  • Hierarchical clustering. Grouping samples and genes with similar patterns together using dendrograms.
  • Row scaling (z-score normalisation). Centering gene expression around zero so that relative upregulation (higher expression) and downregulation (lower expression) across conditions stand out regardless of baseline abundance.
  • Sample annotations. Overlaying experimental metadata — such as treatment status or cell line — along the columns to immediately evaluate the independent variables.

2. R packages we'll be using

To follow along, you will need a few core Bioconductor and CRAN libraries:

  • airway: contains a benchmark RNA-seq dataset from human airway smooth muscle cells treated with dexamethasone.
  • DESeq2: performs differential gene expression analysis and variance-stabilising transformations.
  • pheatmap: provides fine-grained control over heatmap layout, annotations, clustering metrics, and file exports.
  • AnnotationDbi and org.Hs.eg.db: map Ensembl gene identifiers to standard, human-readable gene symbols.
1# Install BiocManager and required packages if not already installed:
2# if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager")
3# if (!require("airway")) BiocManager::install("airway")
4# if (!require("DESeq2")) BiocManager::install("DESeq2")
5# if (!require("pheatmap")) install.packages("pheatmap")
6# if (!require("AnnotationDbi")) BiocManager::install("AnnotationDbi")
7# if (!require("org.Hs.eg.db")) BiocManager::install("org.Hs.eg.db")
8
9library(airway)
10library(DESeq2)
11library(pheatmap)
12library(AnnotationDbi)
13library(org.Hs.eg.db)

3. Step-by-step implementation

Step 1. Load data and run differential expression analysis

We load the airway dataset, format sample metadata, and fit a DESeq2 differential expression model to identify significantly altered genes.

1# --- Load Data and Prep Metadata ---
2data("airway")
3colnames(airway) <- gsub(" ", "_", colnames(airway))
4airway$dex <- as.factor(airway$dex)
5airway$cell <- as.factor(airway$cell)
6
7# --- Construct DESeq2 Object and Filter Low Counts ---
8dds <- DESeqDataSet(airway, design = ~ cell + dex)
9keep <- rowSums(counts(dds)) >= 10
10dds <- dds[keep, ]
11
12# --- Run DESeq Analysis and Order Results ---
13dds <- DESeq(dds)
14res <- results(dds)
15res <- na.omit(res)
16res <- res[order(res$padj), ]

Step 2. Map Ensembl IDs to readable gene symbols

Raw Ensembl IDs (e.g., ENSG00000101347) are difficult to interpret. We strip version suffixes and map the IDs to standard gene symbols using org.Hs.eg.db.

1# --- Clean Ensembl IDs ---
2ens_ids <- sub("\\.\\d+$", "", rownames(res))
3
4# --- Offline Symbol Mapping ---
5map_symbols <- AnnotationDbi::select(
6 org.Hs.eg.db,
7 keys = ens_ids,
8 keytype = "ENSEMBL",
9 columns = c("SYMBOL", "GENENAME")
10)
11
12# --- Remove duplicates and align with results ---
13map_symbols <- map_symbols[!duplicated(map_symbols$ENSEMBL), ]
14symbol_vec <- map_symbols$SYMBOL[match(ens_ids, map_symbols$ENSEMBL)]
15
16# --- Fallback to Ensembl ID if symbol is missing ---
17label_vec <- ifelse(is.na(symbol_vec) | symbol_vec == "", ens_ids, symbol_vec)
18
19# --- Attach cleaned IDs and symbols to results ---
20res$ENSEMBL_clean <- ens_ids
21res$label <- label_vec

Step 3. Extract top genes and prepare expression matrix

We select the top 20 differentially expressed genes, transform counts using Variance Stabilising Transformation (vst), and mean-centre the rows so relative expression changes are highlighted.

1# --- Select Top 20 Genes ---
2top_n <- 20
3top_genes_ens <- head(res$ENSEMBL_clean, top_n)
4top_labels <- head(res$label, top_n)
5
6# --- Variance Stabilising Transformation ---
7vsd <- vst(dds, blind = FALSE)
8
9# --- Format column names for clarity ---
10sample_info <- colData(vsd)
11colnames(vsd) <- paste(sample_info$cell, sample_info$dex, sep = "_")
12
13# --- Match row identifiers ---
14assay_ids <- sub("\\.\\d+$", "", rownames(vsd))
15rownames(vsd) <- assay_ids
16
17# --- Subset and Mean-Centre Matrix ---
18mat <- assay(vsd)[top_genes_ens, , drop = FALSE]
19mat <- mat - rowMeans(mat)
20rownames(mat) <- top_labels

Step 4. Configure annotations and generate heatmap

We set up column annotations (treatment and cell line) with custom colour schemes, generate the clustered heatmap (Figure 1), and export the output directly to a high-resolution PNG file.

1# --- Build Column Metadata ---
2annotation_col <- as.data.frame(colData(vsd)[, c("dex", "cell")])
3colnames(annotation_col) <- c("Dexamethasone", "Cell line")
4
5annotation_col$Dexamethasone <- factor(
6 annotation_col$Dexamethasone,
7 levels = c("untrt", "trt"),
8 labels = c("untreated", "treated")
9)
10rownames(annotation_col) <- colnames(mat)
11
12# --- Custom Colour Palettes ---
13ann_colors <- list(
14 `Dexamethasone` = c(
15 "untreated" = "white",
16 "treated" = "gray"
17 ),
18 `Cell line` = c(
19 "N052611" = "#468189",
20 "N061011" = "#77aca2",
21 "N080611" = "#9dbebb",
22 "N61311" = "#f4e9cd"
23 )
24)
25
26# --- Plot Heatmap (Displays in RStudio) ---
27ph <- pheatmap(
28 mat,
29 annotation_col = annotation_col,
30 annotation_colors = ann_colors,
31 scale = "row",
32 clustering_distance_rows = "correlation",
33 clustering_distance_cols = "correlation",
34 main = sprintf("Top %d Differentially Expressed Genes", top_n),
35 fontsize = 14
36)
37
38# --- Export Heatmap to PNG ---
39png("top_20_genes_heatmap.png", width = 10, height = 8, units = "in", res = 300)
40grid::grid.draw(ph$gtable)
41dev.off()
Clustered heatmap of the top 20 differentially expressed genes in four human airway smooth muscle cell lines, untreated and treated with dexamethasone

Figure 1. Heatmap of top 20 differentially expressed genes in four human airway smooth muscle cell lines untreated treated with dexamethasone.

Interpreting the results

The heatmap displays the relative expression profiles of the top 20 differentially expressed genes across four human airway smooth muscle cell lines, comparing untreated controls (untrt) against dexamethasone-treated (trt) cells:

  • Clear treatment clustering: The column dendrogram perfectly splits the samples into two main branches based on treatment status — all four untreated samples cluster together on the left, while all four treated samples cluster on the right. This demonstrates that dexamethasone treatment drives the primary source of transcriptomic variation, overriding baseline differences between cell lines.
  • Bi-directional gene expression modules: Row clustering reveals two primary gene modules in the dexamethasone-treated cells:
  • Downregulated genes (top cluster): A small module containing the genes CXCL12, ADAM12, VCAM1, and KCTD12 shows high relative expression (orange/red) in untreated samples, but strong downregulation (blue) following dexamethasone treatment.
  • Upregulated genes (bottom cluster): The vast majority of top genes (including PER1, DUSP1, SAMHD1, and KLF15) show consistent upregulation (orange/red) in response to treatment compared to lower baseline levels (blue) in untreated controls.
  • Row z-score scaling: Mean-centring and scaling relative expression highlights these relative fold changes clearly, making it easy to spot consistent variations in biological mechanisms (such as glucocorticoid-induced anti-inflammatory signaling) across independent cell lines.

Summary

Combining DESeq2 variance-stabilised counts with pheatmap allows you to transform raw sequencing reads into informative visual summaries. Adding sample metadata annotations and converting raw gene identifiers to standard symbols ensures your figures are clear, interpretable, and ready for publication.

View the full code.

#r#heatmap#pheatmap#deseq2#rna-seq
Written by
Dr. Gabija Vaitkevičiūtė
Research Scientist

Molecular biology, agronomy, and experimental design — translating wet-lab questions into sound statistical plans.

LinkedIn →
WE HELP SCIENTISTS BE SCIENTISTS

Let's get your data publication-ready

Book a free 20-minute consultation. We'll scope your analysis and tell you exactly what it takes to publish.

Book a consultation →