Show Sidebar Hide Sidebar

geom_tile in ggplot2

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

New to Plotly?

Plotly's R library is free and open source!
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 geom_tile graph

This graph, compiled by Jeff Zimmerman, shows how often hitters swing and miss at fastballs, based on their velocity and spin rate. Colour schemes are from ColorBrewer; a complete list of palettes is available here.

library(plotly)
stringsAsFactors = FALSE)

p <- ggplot(spinrates, aes(x=velocity, y=spinrate)) +
geom_tile(aes(fill = swing_miss)) +
scale_fill_distiller(palette = "YlGnBu") +
labs(title = "Likelihood of swinging and missing on a fastball",
y = "spin rate (rpm)")

ggplotly(p)


The direction option sets which side of the colour scheme maps onto the low values and which side maps onto the high; it defaults to -1 but could be adjusted to 1.

library(plotly)
stringsAsFactors = FALSE)

p <- ggplot(spinrates, aes(x=velocity, y=spinrate)) +
geom_tile(aes(fill = swing_miss)) +
scale_fill_distiller(palette = "YlGnBu", direction = 1) +
theme_light() +
labs(title = "Likelihood of swinging and missing on a fastball",
y = "spin rate (rpm)")

ggplotly(p)


geom_tile with viridis colour scheme

Viridis colour schemes are uniform in both colour and black-and-white, as well as for those with colour-blindness. There are five colour schemes: "magma" (or "A"), "inferno" (or "B"), "plasma" (or "C"), "viridis" (or "D", the default option) and "cividis" (or "E").

library(plotly)