• Open Source.
    These libraries are free forever. Your Pro plan helps keep them top notch.
  • Share Online.
    Share charts, dashboards, Jupyter notebooks, and presentations through our enterprise-grade cloud.
  • Engineering Support.
    Get instant chat support from our awesome engineering team.
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.5.2'

Basic Heatmap

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

# Create a shareable link to your chart
# Set up API credentials: https://plot.ly/r/getting-started
chart_link = plotly_POST(p, filename="heatmap/simple")
chart_link

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

# Create a shareable link to your chart
# Set up API credentials: https://plot.ly/r/getting-started
chart_link = plotly_POST(p, filename="heatmap/cat")
chart_link

Sequential Colorscales: Greys

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

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

# Create a shareable link to your chart
# Set up API credentials: https://plot.ly/r/getting-started
chart_link = plotly_POST(p, filename="heatmap/gray")
chart_link

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

# Create a shareable link to your chart
# Set up API credentials: https://plot.ly/r/getting-started
chart_link = plotly_POST(p, filename="heatmap/ramp")
chart_link

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

# Create a shareable link to your chart
# Set up API credentials: https://plot.ly/r/getting-started
chart_link = plotly_POST(p, filename="heatmap/custom")
chart_link
Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to our Premium or Enterprise plans.