Get startedGet started for free

Adding a custom continuous color palette to ggplot2 plots

The most versatile way to add a custom continuous scale to ggplot2 plots is with scale_color_gradientn() or scale_fill_gradientn(). How do you know which to use? Match the function to the aesthetic you have mapped. For example, in your plot of predicted house price from Chapter 1, you mapped fill to price, so you'd need to use scale_fill_gradientn().

These two functions take an argument colors where you pass a vector of colors that defines your palette. This is where the versatility comes in. You can generate your palette in any way you choose, automatically using something like RColorBrewer or viridisLite, or manually by specifying colors by name or hex code.

The scale___gradientn() functions handle how these colors are mapped to values of your variable, although there is control available through the values argument.

Let's play with some alternative color scales for your predicted house price heatmap from Chapter 1 (we've dropped the map background to reduce computation time, so you can see your plots quickly).

This exercise is part of the course

Visualizing Geospatial Data in R

View Course

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

library(RColorBrewer)
# 9 steps on the RColorBrewer "BuPu" palette: blups


# Add scale_fill_gradientn() with the blups palette
ggplot(preds) +
  geom_tile(aes(lon, lat, fill = predicted_price), alpha = 0.8) 
Edit and Run Code