Skip to main content

9  Heatmaps

library(rtemis.draw)

draw_heatmap() draws a numeric matrix as colored cells, with optional clustering, dendrograms, cell values and notes, and color tracks.

9.1 Correlation matrix

draw_heatmap() accepts any numeric matrix. For square matrices, square_cells is enabled automatically so every cell is square. This also applies to SVG exports and draw_panels() figures; the matrix fits within the allocated canvas while retaining its square cells.

Set zlim = c(-1, 1) to fix the color scale to the full correlation range:

num_vars <- c("bill_len", "bill_dep", "flipper_len", "body_mass")
m <- cor(na.omit(penguins[, num_vars]))
draw_heatmap(m, zlim = c(-1, 1), title = "Penguin Correlations")

9.2 Lower triangle

For symmetric matrices it is common to show only one triangle. Use triangle = "lower" to keep the lower triangle and diagonal, masking the upper triangle:

draw_heatmap(m, triangle = "lower", zlim = c(-1, 1))

9.3 Cell values

Set show_values = TRUE to print each correlation coefficient inside its cell. value_digits controls the number of decimal places and defaults to two:

draw_heatmap(
  m,
  triangle = "lower",
  zlim = c(-1, 1),
  show_values = TRUE,
  value_digits = 2
)

9.4 Hierarchical clustering

The order of the rows and columns decides whether a heatmap shows structure. The example simulates the expression of 36 genes in 250 samples. Each gene belongs to one of six co-expression modules, A to F, and follows its module’s latent factor plus independent noise; the factors of modules A and B correlate positively, and those of modules C and D negatively. The genes are then shuffled, and in this order the correlation matrix shows no pattern:

set.seed(2026)
module_sizes <- c(A = 8, B = 5, C = 7, D = 6, E = 4, F = 6)
factor_cor <- diag(6)
factor_cor[1, 2] <- factor_cor[2, 1] <- 0.45
factor_cor[3, 4] <- factor_cor[4, 3] <- -0.6
n <- 250
factors <- matrix(rnorm(n * 6), n) %*% chol(factor_cor)
genes <- do.call(cbind, lapply(seq_along(module_sizes), function(j) {
  loading <- runif(module_sizes[[j]], 0.6, 0.9)
  noise <- matrix(rnorm(n * module_sizes[[j]]), n)
  outer(factors[, j], loading) + sweep(noise, 2, sqrt(1 - loading^2), "*")
}))
colnames(genes) <- paste0(rep(names(module_sizes), module_sizes), sequence(module_sizes))
genes <- genes[, sample(ncol(genes))]
gene_cor <- cor(genes)

draw_heatmap(gene_cor, zlim = c(-1, 1), title = "Gene correlations, shuffled")

cluster_rows and cluster_cols reorder the matrix by hierarchical clustering: dist() with dist_method computes the distances between rows, and between columns, and hclust() with hclust_method joins them into the trees drawn as dendrograms. Ordered by the trees, the six modules form blocks along the diagonal, the opposed modules C and D form a negative block beside it, and the related modules A and B join in the tree before the others. row_cut and col_cut cut each tree into that many clusters and color their branches:

draw_heatmap(
  gene_cor,
  cluster_rows = TRUE,
  cluster_cols = TRUE,
  hclust_method = "average",
  row_cut = 6L,
  col_cut = 6L,
  zlim = c(-1, 1),
  title = "Gene correlations, clustered"
)

9.5 Rectangular matrices

For rectangular matrices, set square_cells = FALSE. This example computes the mean of each trait per species and z-scores the columns so traits on different scales are directly comparable:

traits <- c("bill_len", "bill_dep", "flipper_len", "body_mass")
means <- sapply(
  traits,
  function(tr) tapply(penguins[[tr]], penguins$species, mean, na.rm = TRUE)
)
colnames(means) <- c("Bill Length", "Bill Depth", "Flipper Length", "Body Mass")

draw_heatmap(
  scale(means),
  square_cells = FALSE,
  show_values = TRUE,
  value_digits = 2,
  title = "Mean Traits by Species (z-scored)"
)

9.6 Trees and annotations

Supply a saved hclust or dendrogram to reuse a clustering result. Labeled leaves match the original matrix names; their order is applied to values, notes, and color tracks together. Trees without labels use input positions. row_cut and col_cut color branches within the requested clusters.

trait_values <- scale(means)
trait_tree <- hclust(dist(trait_values))
trait_notes <- matrix(
  sprintf("%.2f SD", trait_values),
  nrow = nrow(trait_values), dimnames = dimnames(trait_values)
)
species_colors <- c("#18A3AC", "#F48024", "#8C6BB1")
draw_heatmap(
  trait_values, row_tree = trait_tree, row_cut = 2L,
  cell_notes = trait_notes, show_notes = TRUE,
  row_colors = species_colors, square_cells = FALSE,
  title = "Standardized traits with saved clustering"
)

Notes appear on hover; show_notes = TRUE also prints them in cells, including SVG exports. Long visible notes truncate to the cell width; hover retains the full text. Choose notes or numeric show_values labels. Color tracks accept R colors, with one row per matrix identity and one column per track. Named annotations align by identity; unnamed annotations use input positions.

For saved configurations, bind a data record containing values and any of row_tree, col_tree, cell_notes, row_colors, or col_colors. Presentation settings such as show_notes and row_cut belong in setup_HeatmapConfig(). Supplied trees take precedence over computed clustering and require a full matrix; triangle masking removes leaves and cannot be combined with them.

9.7 Configuration

setup_HeatmapConfig() describes a heatmap’s display; draw() binds it to a matrix:

config <- setup_HeatmapConfig(triangle = "lower", show_values = TRUE,
                              zlim = c(-1, 1))
draw(config, data = m)
© 2026 E.D. Gennatas