Session Ready
Exercise

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

Instructions 1/3
undefined XP
  • 1
    • Create a palette called blups from 9 steps on the RColorBrewer palette "BuPu".
    • Add scale_fill_gradientn() and pass the blups palette as the colors argument.
    • 2
      • Create a palette called vir from 9 steps on the viridis() palette from viridisLite.
      • Add scale_fill_gradientn() and pass the vir palette as the colors argument.
    • 3
      • Create a palette called mag from 9 steps on the magma() palette from viridisLite.
      • Add scale_fill_gradientn() and pass the mag palette as the colors argument.