Skip to content

ComplexHeatmap

ComplexHeatmap draws heatmaps with grid graphics. Heatmap() builds an object, and draw() renders it on the open graphics device. Annotations, splits, and several heatmaps side by side all attach to that object before you draw it. The examples run in ComplexHeatmap 2.28.0 on the airway data, eight airway smooth muscle samples from four cell lines, each untreated and treated with dexamethasone.

Function or argument Purpose
Heatmap(mat, name = ) Build one heatmap
draw(ht) Render on the open device and return the drawn object
colorRamp2(breaks, colors) Continuous color scale with fixed breaks
HeatmapAnnotation() Column annotation tracks
rowAnnotation() Row annotation tracks
anno_barplot(), anno_points() Numbers drawn inside an annotation
anno_boxplot(mat) One boxplot per column or row of a matrix
rowAnnotation(mark = anno_mark(at = , labels = )) Label selected rows when names are hidden
row_split, column_split One panel per factor level
row_km, column_km Panels from k-means clusters
cluster_row_slices = FALSE Keep panels in factor order
clustering_distance_rows "euclidean", "pearson", "spearman", or a function
clustering_method_rows "complete", "average", "ward.D2"
ht1 + ht2 Heatmaps side by side with a shared row order
row_order(drawn), column_order(drawn) Order after clustering
oncoPrint() Mutations by gene and sample

Convert the counts to log2 CPM, keep the well expressed genes, and pick the 15 genes that rise most and the 15 that fall most with treatment. The z-score scales each gene to mean 0 and standard deviation 1 across the samples, so the colors compare samples within a gene.

The count object comes from Michael Love’s airway 1.32.0 data package, which declares LGPL. It represents the Himes and colleagues experiment, deposited as GSE52778 and SRP033351. The source and license notice identifies the original object. This lesson derives its summaries and figures from that object.

library(ComplexHeatmap)
library(circlize)
library(SummarizedExperiment)
library(airway)
set.seed(42)
dir.create("outputs", showWarnings = FALSE)
data(airway)
counts <- assay(airway, "counts")
log_cpm <- log2(sweep(counts, 2, colSums(counts), "/") * 1e6 + 1)
colnames(log_cpm) <- paste(airway$cell, airway$dex, sep = "_")
expressed <- log_cpm[rowMeans(log_cpm) > 5, ]
treated <- airway$dex == "trt"
lfc <- rowMeans(expressed[, treated]) - rowMeans(expressed[, !treated])
top_ids <- c(names(sort(lfc, decreasing = TRUE))[1:15], names(sort(lfc))[1:15])
mat <- t(scale(t(expressed[top_ids, ])))
rownames(mat) <- rowData(airway)[top_ids, "gene_name"]
gene_lfc <- unname(lfc[top_ids])
round(mat[1:4, 1:4], 2)
N61311_untrt N61311_trt N052611_untrt N052611_trt
FKBP5 -0.98 1.01 -0.87 1.03
SAMHD1 -0.91 0.84 -0.88 1.10
GPX3 -1.27 0.80 -0.55 1.25
MAOA -0.86 0.94 -0.81 0.97

name sets the legend title. Rows and columns are clustered by default with Euclidean distance and complete linkage. Open a device, call draw(), then close the device. invisible() stops dev.off() from printing the device number.

ht_basic <- Heatmap(
mat,
name = "z-score",
row_names_gp = gpar(fontsize = 8),
column_names_gp = gpar(fontsize = 9)
)
png("outputs/complexheatmap-basic.png",
width = 6.5, height = 7, units = "in", res = 150)
draw(ht_basic)
invisible(dev.off())

Heatmap of 30 airway genes by eight samples in the default blue, white and red scale with dendrograms on the rows and columns. The column dendrogram separates the four treated samples on the left from the four untreated samples on the right. The upper 15 genes, from PTX3 to ADARB1, are red in treated samples and blue in untreated samples, and the lower 15 genes, from TNFRSF11B to ITGA11, show the reverse.

colorRamp2() from circlize returns a function that maps numbers to colors. Values between the breaks are interpolated, and values beyond the outer breaks get the end colors.

col_fun <- colorRamp2(c(-2, 0, 2), c("#2166AC", "white", "#B2182B"))
col_fun(c(-3, -1, 0, 1, 3))
[1] "#2166ACFF" "#9CAFD6FF" "#FFFFFFFF" "#E4948EFF" "#B2182BFF"

Fix the breaks yourself when you compare heatmaps. Without col, each heatmap picks its own range from the data.

HeatmapAnnotation() adds tracks along the columns and rowAnnotation() adds tracks along the rows. A named vector of colors per track keeps each level on a fixed color. anno_barplot() draws a number per row, here the treated minus untreated difference in log2 CPM.

col_ha <- HeatmapAnnotation(
Treatment = airway$dex,
Cell = airway$cell,
col = list(
Treatment = c(untrt = "grey70", trt = "#E64B35"),
Cell = c(
N61311 = "#66C2A5", N052611 = "#FC8D62",
N080611 = "#8DA0CB", N061011 = "#E78AC3"
)
)
)
row_ha <- rowAnnotation(
LFC = anno_barplot(
gene_lfc, width = unit(2, "cm"),
gp = gpar(fill = ifelse(gene_lfc > 0, "#B2182B", "#2166AC"))
)
)
ht_annotated <- Heatmap(
mat,
name = "z-score",
col = col_fun,
top_annotation = col_ha,
right_annotation = row_ha,
row_names_gp = gpar(fontsize = 8),
show_column_names = FALSE
)
png("outputs/complexheatmap-annotated.png",
width = 7, height = 7.5, units = "in", res = 150)
draw(ht_annotated)
invisible(dev.off())

The same heatmap in a fixed blue to red scale from -2 to 2, with a Treatment track and a Cell track above the columns and a bar chart of the fold change on the right. The treated block is red on the Treatment track and the four cell lines alternate in green, orange, blue and pink. The bars point right, up to about 3.9 for FKBP5, for the upper 15 genes and left, down to about -2.6 for KCTD12, for the lower 15 genes.

anno_boxplot() draws one box per column of the matrix it receives. Here it shows the log2 CPM of the 30 genes in each sample above their z-scores, so the annotation keeps the scale the z-score removes.

box_ha <- HeatmapAnnotation(
log2_CPM = anno_boxplot(
expressed[top_ids, ], height = unit(2.5, "cm"),
gp = gpar(fill = ifelse(treated, "#E64B35", "grey70"))
),
annotation_name_side = "left"
)
ht_box <- Heatmap(
mat,
name = "z-score",
col = col_fun,
top_annotation = box_ha,
row_names_gp = gpar(fontsize = 8),
column_names_gp = gpar(fontsize = 9)
)
png("outputs/complexheatmap-anno-boxplot.png",
width = 6.5, height = 8, units = "in", res = 150)
draw(ht_box)
invisible(dev.off())

The 30-gene z-score heatmap with a boxplot annotation above it, one box per sample of log2 CPM on an axis from 2 to 10. The four treated boxes are red with medians near 7, and the four untreated boxes are grey with medians near 6.5. The column dendrogram above the boxes separates the treated from the untreated samples.

With hundreds of rows, the row names overlap. Hide them and use anno_mark() to point at the rows you care about. at takes row indices in the input matrix, and the labels follow the rows after clustering. KLF15 and PER1 are not among the 200 genes with the largest change, so which() keeps four of the six markers.

tall_ids <- names(sort(abs(lfc), decreasing = TRUE))[1:200]
tall_mat <- t(scale(t(expressed[tall_ids, ])))
tall_symbols <- rowData(airway)[tall_ids, "gene_name"]
marker_genes <- c("FKBP5", "TSC22D3", "DUSP1", "KLF15", "PER1", "CRISPLD2")
mark_at <- which(tall_symbols %in% marker_genes)
tall_symbols[mark_at]
[1] "FKBP5" "TSC22D3" "DUSP1" "CRISPLD2"
ht_tall <- Heatmap(
tall_mat,
name = "z-score",
col = col_fun,
top_annotation = col_ha,
show_row_names = FALSE,
show_column_names = FALSE,
show_row_dend = FALSE,
right_annotation = rowAnnotation(
mark = anno_mark(
at = mark_at, labels = tall_symbols[mark_at],
labels_gp = gpar(fontsize = 9)
)
)
)
png("outputs/complexheatmap-anno-mark.png",
width = 6, height = 7, units = "in", res = 150)
draw(ht_tall)
invisible(dev.off())

Heatmap of the 200 genes with the largest treatment change, with no row names, the Treatment and Cell tracks on top, and the columns split by the dendrogram into treated and untreated. Lines on the right point from four rows to the labels FKBP5, near the top, and CRISPLD2, TSC22D3 and DUSP1, about two thirds of the way down in the block that is higher in treated samples.

row_split and column_split take a factor and draw one panel per level. Clustering then runs inside each panel. cluster_row_slices = FALSE keeps the panels in factor order. To split by k-means instead, pass row_km = 2 and set a seed first.

direction <- factor(
ifelse(gene_lfc > 0, "Up with dex", "Down with dex"),
levels = c("Up with dex", "Down with dex")
)
ht_split <- Heatmap(
mat,
name = "z-score",
col = col_fun,
top_annotation = col_ha,
row_split = direction,
column_split = airway$dex,
cluster_row_slices = FALSE,
row_title_rot = 0,
row_names_gp = gpar(fontsize = 8),
show_column_names = FALSE
)
png("outputs/complexheatmap-split.png",
width = 7.5, height = 7.5, units = "in", res = 150)
ht_split_drawn <- draw(ht_split)
invisible(dev.off())

Heatmap split into four panels. Columns split into untrt and trt, and rows split into Up with dex, with 15 genes from PTX3 to ADARB1, and Down with dex, with 15 genes from TNFRSF11B to ITGA11. The Up with dex panel is blue in untreated and red in treated samples, and the Down with dex panel is the reverse.

draw() returns the drawn object. row_order() on it gives the row indices from top to bottom, as a list with one element per slice when the rows are split.

split_order <- row_order(ht_split_drawn)
lapply(split_order, \(index) rownames(mat)[index])
$`Up with dex`
[1] "PTX3" "ADAMTS1" "CCDC69" "GPX3" "DUSP1" "SAMHD1"
[7] "GLUL" "CRISPLD2" "TSC22D3" "ADAMTS5" "ERRFI1" "FKBP5"
[13] "MAOA" "C7" "ADARB1"
$`Down with dex`
[1] "TNFRSF11B" "FST" "OLFML2A" "CRABP2" "ADAM12" "KCTD12"
[7] "TBX18" "SOX4" "BDKRB2" "DNM1" "CXCL12" "ACKR4"
[13] "CLDN11" "LRRC17" "ITGA11"

Take the order from the drawn object. The object that Heatmap() returns has not been clustered yet.

+ joins heatmaps into a list that shares the row order of the first one. Here a one-column heatmap of the fold change sits next to the z-scores, with its own color scale. The row names belong to the last heatmap in the list, so set their font there.

lfc_mat <- matrix(gene_lfc, ncol = 1, dimnames = list(rownames(mat), "LFC"))
lfc_col <- colorRamp2(c(-4, 0, 4), c("#1B7837", "white", "#762A83"))
ht_z <- Heatmap(
mat, name = "z-score", col = col_fun,
top_annotation = col_ha, show_column_names = FALSE,
column_title = "Expression"
)
ht_lfc <- Heatmap(
lfc_mat, name = "log2 FC", col = lfc_col,
width = unit(1, "cm"), column_title = "Change",
row_names_gp = gpar(fontsize = 8)
)
png("outputs/complexheatmap-list.png",
width = 8, height = 7.5, units = "in", res = 150)
draw(ht_z + ht_lfc, ht_gap = unit(4, "mm"))
invisible(dev.off())

Two heatmaps side by side that share one row order. The left heatmap, titled Expression, shows the z-scores with the Treatment and Cell tracks. The right one-column heatmap, titled Change, shows the log2 fold change in purple for the 15 upregulated genes and green for the 15 downregulated genes, with separate legends for z-score and log2 FC.

clustering_distance_rows takes a method name such as "pearson" or "spearman", and clustering_method_rows takes an hclust() linkage. heatmap_legend_param sets the legend title, breaks, and size.

ht_options <- Heatmap(
mat,
name = "z-score",
col = col_fun,
clustering_distance_rows = "pearson",
clustering_method_rows = "ward.D2",
show_column_dend = FALSE,
row_dend_width = unit(2, "cm"),
row_names_gp = gpar(fontsize = 8),
column_names_gp = gpar(fontsize = 9),
heatmap_legend_param = list(
title = "Expression\nz-score",
at = c(-2, -1, 0, 1, 2),
legend_height = unit(4, "cm")
)
)
png("outputs/complexheatmap-options.png",
width = 6.5, height = 7, units = "in", res = 150)
draw(ht_options)
invisible(dev.off())

Heatmap clustered on rows with Pearson distance and Ward linkage and with no column dendrogram. The row dendrogram splits into two main branches, the downregulated genes from TNFRSF11B to ITGA11 on top and the upregulated genes from PTX3 to ADARB1 below. The legend is titled Expression z-score with breaks at -2, -1, 0, 1 and 2.

oncoPrint() draws one tile per gene and sample from a character matrix of genes by samples. Each cell holds the alteration types separated by ;, and alter_fun says how to draw each type. Genes sort by alteration frequency, and the bars on top and on the right count the alterations.

The drawing list corresponds to Zuguang Gu’s oncoPrint book example, including the background rectangle and mutation height of 0.33. The book repository dedicates its content under CC0. This lesson generates different alteration data and changes the deletion label and colors.

genes <- c("TP53", "KRAS", "PIK3CA", "EGFR", "PTEN", "CDKN2A")
patients <- sprintf("T%02d", 1:20)
alteration_rate <- c(0.55, 0.35, 0.3, 0.2, 0.2, 0.25)
mut <- matrix("", nrow = length(genes), ncol = length(patients),
dimnames = list(genes, patients))
for (i in seq_along(genes)) {
hit <- runif(length(patients)) < alteration_rate[i]
mut[i, hit] <- sample(c("MUT", "AMP", "DEL", "MUT;AMP"), sum(hit),
replace = TRUE, prob = c(0.6, 0.15, 0.15, 0.1))
}
alter_colors <- c(MUT = "#008000", AMP = "#E41A1C", DEL = "#377EB8")
alter_fun <- list(
background = alter_graphic("rect", fill = "#E5E5E5"),
AMP = alter_graphic("rect", fill = alter_colors["AMP"]),
DEL = alter_graphic("rect", fill = alter_colors["DEL"]),
MUT = alter_graphic("rect", height = 0.33, fill = alter_colors["MUT"])
)
ht_onco <- oncoPrint(
mut,
alter_fun = alter_fun,
col = alter_colors,
column_title = "Simulated alterations in 20 tumors",
heatmap_legend_param = list(title = "Alteration")
)
png("outputs/complexheatmap-oncoprint.png",
width = 8, height = 4, units = "in", res = 150)
draw(ht_onco)
invisible(dev.off())

oncoPrint of six genes in 20 simulated tumors. TP53 and PIK3CA are each altered in 40% of tumors, KRAS, CDKN2A and EGFR in 20%, and PTEN in 10%. Amplifications are red rectangles, deletions blue rectangles and mutations thin green bars, with a stacked count per tumor on top and per gene on the right.

alter_graphic() builds the drawing functions, so you do not write a function(x, y, w, h) for each type.

Any device works the same way. PDF keeps the cells and text as vectors for a journal figure.

pdf("outputs/complexheatmap-annotated.pdf", width = 7, height = 7.5)
draw(ht_annotated)
invisible(dev.off())
  • Clustered Heatmap draws a z-scored expression heatmap with a sample annotation in R and Python.
  • RNA-seq Visualization builds the heatmap of the top genes from a full DESeq2 analysis of the same airway data.
  • RNA-seq Normalization explains DESeq2 size factors and the variance-stabilizing transform, the usual alternative to log CPM for a heatmap.

Himes and colleagues, 2014 report the airway experiment used here.

Gu, Eils, and Schlesner, 2016 describe ComplexHeatmap and its heatmaps for multidimensional genomic data.

The single heatmap chapter explains fixed color scales, row and column splits, and the order returned after draw(). Those sections distinguish the values shown in the matrix from the clustering and annotation choices.

The oncoPrint chapter explains how alteration strings become layered rectangles and how alter_graphic() builds their drawing functions. It also describes the row frequencies and bar annotations in the simulated tumor example.