Show Sidebar Hide Sidebar

Heatmaps in R

How to make a heatmap in R with a matrix. Seven examples of colored and labeled heatmaps with custom colorscales.

New to Plotly?

Plotly's R library is free and open source!
Get started by downloading the client and reading the primer.
You can set up Plotly to work in online or offline mode.
We also have a quick-reference cheatsheet (new!) to help you get started!

Version Check

Version 4 of Plotly's R package is now available!
Check out this post for more information on breaking changes and new features available in this version.

## [1] '4.9.1'

Basic Heatmap

p <- plot_ly(z = volcano, type = "heatmap")


Categorical Axes

m <- matrix(rnorm(9), nrow = 3, ncol = 3)
p <- plot_ly(
    x = c("a", "b", "c"), y = c("d", "e", "f"),
    z = m, type = "heatmap"


Sequential Colorscales: Greys

The colors argument understands color brewer palettes (see for valid names).

p <- plot_ly(z = volcano, colors = "Greys", type = "heatmap")


Custom colorscales

The colors argument also accepts a color interpolation function like colorRamp()

p <- plot_ly(z = volcano, colors = colorRamp(c("red", "green")), type = "heatmap")


Or, you can do the scaling yourself and use the colorscale attribute directly...

vals <- unique(scales::rescale(c(volcano)))
o <- order(vals, decreasing = FALSE)
cols <- scales::col_numeric("Blues", domain = NULL)(vals)
colz <- setNames(data.frame(vals[o], cols[o]), NULL)
p <- plot_ly(z = volcano, colorscale = colz, type = "heatmap")