Enhanced Heat Maps with heatmap.2

Andy Liaw, original; R. Gentleman, M. Maechler, W. Huber, G. Warnes, revisions. Tal Galili

2025-11-29

Introduction

The heatmap.2 function provides an enhanced version of the standard R heatmap function with numerous additional features and customization options. This vignette demonstrates the key capabilities and usage patterns of heatmap.2. It is based on the manual for ?heatmap.2, written by Andy Liaw, original; R. Gentleman, M. Maechler, W. Huber, G. Warnes, revisions.

Details on Dendrograms, Scaling, and Plot Layout

Dendrogram Behavior (Rowv, Colv)

Data Scaling (scale)

Color Selection

Plot Layout (Default and Customization)

Note

Load Data

Code
# Load required libraries
library(gplots)  # for heatmap.2
library(RColorBrewer)  # for better color palettes
Code
data(mtcars)
x  <- as.matrix(mtcars)
rc <- rainbow(nrow(x), start=0, end=.3)
cc <- rainbow(ncol(x), start=0, end=.3)

Dendrogram Options

demonstrate the effect of row and column dendrogram options

Code
heatmap.2(x)                    ## default - dendrogram plotted and reordering done.

Code
heatmap.2(x, dendrogram="none") ##  no dendrogram plotted, but reordering done.

Code
heatmap.2(x, dendrogram="row")  ## row dendrogram plotted and row reordering done.

Code
heatmap.2(x, dendrogram="col")  ## col dendrogram plotted and col reordering done.

Code
heatmap.2(x, keysize=2)         ## default - dendrogram plotted and reordering done.

Code
heatmap.2(x, Rowv=FALSE, dendrogram="both") ## generates a warning!

Code
heatmap.2(x, Rowv=NULL, dendrogram="both")  ## generates a warning!
heatmap.2(x, Colv=FALSE, dendrogram="both") ## generates a warning!

Reorder dendrogram by branch means rather than sums

Code
heatmap.2(x, reorderfun=function(d, w) reorder(d, w, agglo.FUN = mean) )

Color dendrograms’ branches (using dendextend)

Code
full <- heatmap.2(x) # we use it to easily get the dendrograms
Code
library(dendextend)  # for color_branches
heatmap.2(x, 
        Rowv=color_branches(full$rowDendrogram, k = 3),
        Colv=color_branches(full$colDendrogram, k = 2))

Code
# Look at the vignette for more details:
# https://cran.r-project.org/web/packages/dendextend/vignettes/dendextend.html

plot a sub-cluster using the same color coding as for the full heatmap

Code
full <- heatmap.2(x)

Code
heatmap.2(x, Colv=full$colDendrogram[[2]], breaks=full$breaks)  # column subset

Code
heatmap.2(x, Rowv=full$rowDendrogram[[1]], breaks=full$breaks)  # row subset

Code
heatmap.2(x, Colv=full$colDendrogram[[2]],
            Rowv=full$rowDendrogram[[1]], breaks=full$breaks)  # both

Show effect of row and column label rotation

Code
heatmap.2(x, srtCol=NULL)