Show Sidebar Hide Sidebar

geom_raster in ggplot2

How to make a 2-dimensional heatmap in ggplot2 using geom_raster.

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 2d Heatmap

geom_raster creates a coloured heatmap, with two variables acting as the x- and y-coordinates and a third variable mapping onto a colour. (It is coded similarly to geom_tile and is generated more quickly.) This uses the volcano dataset that comes pre-loaded with R.

library(reshape2)
library(plotly)

df <- melt(volcano)

p <- ggplot(df, aes(Var1, Var2)) +
  geom_raster(aes(fill=value)) +
  labs(x="West to East",
       y="North to South",
       title = "Elevation map of Maunga Whau")

ggplotly(p)

Customized 2d Heatmap

This uses the Spectral palette from ColorBrewer; a full list of palettes is here.

library(reshape2)
library(plotly)

df <- melt(volcano)

p <- ggplot(df, aes(Var1, Var2)) +
  geom_raster(aes(fill=value)) +
  scale_fill_distiller(palette = "Spectral", direction = -1) +
  labs(x="West to East",
       y="North to South",
       title = "Elevation map of Maunga Whau",
       fill = "Elevation") +
  theme(text = element_text(family = 'Fira Sans'),
        plot.title = element_text(hjust = 0.5))

ggplotly(p)