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.
Quick reference
Section titled “Quick reference”| 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_trtFKBP5 -0.98 1.01 -0.87 1.03SAMHD1 -0.91 0.84 -0.88 1.10GPX3 -1.27 0.80 -0.55 1.25MAOA -0.86 0.94 -0.81 0.97Basic heatmap
Section titled “Basic heatmap”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())
Color scale
Section titled “Color scale”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.
Annotations
Section titled “Annotations”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())
Boxplots in a column annotation
Section titled “Boxplots in a column annotation”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())
Label selected genes in a tall heatmap
Section titled “Label selected genes in a tall heatmap”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())
Split rows and columns
Section titled “Split rows and columns”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())
Read the order after clustering
Section titled “Read the order after clustering”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.
Heatmaps side by side
Section titled “Heatmaps side by side”+ 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())
Clustering and legend options
Section titled “Clustering and legend options”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())
oncoPrint
Section titled “oncoPrint”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())
alter_graphic() builds the drawing functions, so you do not write a function(x, y, w, h)
for each type.
Save to PDF
Section titled “Save to PDF”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())See also
Section titled “See also”- 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.
Scientific references
Section titled “Scientific references”Himes and colleagues, 2014 report the airway experiment used here.
Gu, Eils, and Schlesner, 2016 describe ComplexHeatmap and its heatmaps for multidimensional genomic data.
Further reading
Section titled “Further reading”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.