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!
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 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)
spinrates <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/spinrates.csv",
                      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)

Adjusting appearance

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.

Also adjusted the theme.

library(plotly)
spinrates <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/spinrates.csv",
                      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)
spinrates <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/spinrates.csv",
                      stringsAsFactors = FALSE)

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

ggplotly(p)