13.6 Creating a Heat Map

13.6.1 Problem

You want to make a heat map.

13.6.2 Solution

Use geom_tile() or geom_raster() and map a continuous variable to fill. We’ll use the presidents data set, which is a time series object rather than a data frame:

We’ll first convert it to a format that is usable by ggplot: a data frame with columns that are numeric:

Now we can make the plot using geom_tile() or geom_raster() (Figure 13.12). Simply map one variable to x, one to y, and one to fill:

A heat map-the grey squares represent NAs in the data

Figure 13.12: A heat map-the grey squares represent NAs in the data

Note

The results with geom_tile() and geom_raster() should look the same, but in practice they might appear different. See Recipe 6.12 for more information about this issue.

13.6.3 Discussion

To better convey useful information, you may want to customize the appearance of the heat map. With this example, we’ll reverse the y-axis so that it progresses from top to bottom, and we’ll add tick marks every four years along the x-axis, to correspond with each presidential term. For the x and y scales, we remove the padding by using expand=c(0, 0). We’ll also change the color scale using scale_fill_gradient2(), which lets you specify a midpoint color and the two colors at the low and high ends (Figure 13.13):

A heat map with customized appearance

Figure 13.13: A heat map with customized appearance

13.6.4 See Also

If you want to use a different color palette, see Recipe 12.6.