Skip to contents

This function overlays rectangular boundaries on a ComplexHeatmap heatmap to highlight blocks where row and column annotations share the same group label. It detects contiguous segments (blocks) of identical labels in both rows and columns and draws rectangles around all matching row–column block pairs.

Usage

drawRectangleAnnotation(
  ht,
  rows,
  columns,
  col = "black",
  heatmap_name = "hmap",
  include_na = FALSE
)

Arguments

rows

A vector of row annotation labels. Length must match the number of rows in the heatmap.

columns

A vector of column annotation labels. Length must match the number of columns in the heatmap.

col

Character. Color of rectangle borders. Default is "black".

heatmap_name

Character. Name of the heatmap used in decorate_heatmap_body. Must match the name argument used when creating the heatmap. Default is "hmap".

include_na

Logical. Whether to treat NA values as a valid group. If FALSE (default), NA values are ignored when drawing rectangles. If TRUE, NA is treated as a separate group and rectangles may be drawn for missing labels.

Value

This function is called for its side effects and returns NULL. It adds graphical elements (rectangles) to an existing heatmap.

Details

Unlike simpler implementations, this function correctly handles cases where the same annotation label appears in multiple disjoint segments (e.g., after clustering or reordering).

The function performs the following steps:

  • Converts annotation vectors to character format

  • Identifies contiguous blocks of identical labels using run-length encoding

  • Maps block coordinates to the heatmap's normalized coordinate system

  • Draws rectangles around all row–column block pairs sharing the same label

All drawing is performed within decorate_heatmap_body, so the heatmap must already be drawn before calling this function.

Examples

if (FALSE) { # \dontrun{
library(ComplexHeatmap)

mat <- matrix(rnorm(100), 10)
row_ann <- rep(c("A", "B"), each = 5)
col_ann <- rep(c("A", "B"), times = 5)

p1 = Heatmap(mat, name = "hmap")
p1 = draw(p1)
drawRectangleAnnotation(p1,
  rows = row_ann,
  columns = col_ann,
  col = "black"
)
} # }