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.

library(plotly)
packageVersion('plotly')
## [1] '4.9.1'

Basic Heatmap

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

p

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"
)

p

Sequential Colorscales: Greys

The colors argument understands color brewer palettes (see RColorBrewer::brewer.pal.info for valid names).

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

p

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")

p

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")

p