Black Lives Matter. Please consider donating to Black Girls Code today.

# geom_tile in ggplot2

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

New to Plotly?

Plotly is a free and open-source graphing library for R. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

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


Dash for R is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.

Learn about how to install Dash for R at https://dashr.plot.ly/installation.

Everywhere in this page that you see fig, you can display the same figure in a Dash for R application by passing it to the figure argument of the Graph component from the built-in dashCoreComponents package like this:

library(plotly)

fig <- plot_ly()
# fig <- fig %>% add_trace( ... )
# fig <- fig %>% layout( ... )

library(dash)
library(dashCoreComponents)
library(dashHtmlComponents)

app <- Dash$new() app$layout(
htmlDiv(
list(
dccGraph(figure=fig)
)
)
) 