Colours in R

R has famously good looking graphics, and it also has a large collection of beautiful colour palettes. Notable examples include RColorBrewer and viridis, both now available in ggplot2. This list of palettes is a great place to find something that suits you.

Still, sometimes you want to experiment with your own colours. For example, in a recent paper, I used five colours to represent different types of decision, from “egalitarian” to “meritocratic”. I used a blue-yellow-red colour scheme to represent the different decisions, since in the UK, that maps on to the political space, with deep red being the most “left wing” and dark blue the most “right wing”.

dfr <- tibble(height = seq(0.2, 1, .2), factor = letters[1:5])

fair_cols <- c("#38170B","#BF1B0B", "#FFC465", "#66ADE5", "#252A52")
names(fair_cols) <- letters[1:5]

g <- ggplot(dfr, aes(y = height, fill = factor, x = 1)) + 
      geom_col() +

g + scale_fill_manual(values = fair_cols) + 
      labs(title = "ggplot with manual colours")

barplot(dfr$height, col = fair_cols, names.arg = letters[1:5], main = "Base graphics with manual colours")

I like to obsess about graphs – it is a nice break from the very intellectual work of writing an academic paper. So, I might want to tweak those colours, maybe making them brighter or darker.

I could just change the colours in fair_cols. But if you are like me, those strings of hexadecimal may not mean much. It would be hard to tell that #38170B is deep red, for example. And it is quite difficult to edit colours manually. You have to guess how to change the red, green and blue constituents of the colour, then translate that into hexadecimal numbers. All I want to do is make my palette a bit brighter, lighter or darker!

Enter Jon Clayden’s excellent shades library.


shades contains functions to edit colours in natural ways:

g + scale_fill_manual(values = brightness(fair_cols, 0.9)) + 
      labs(title = "Changing brightness")

barplot(dfr$height, col = brightness(fair_cols, 0.9), names.arg = letters[1:5],
      main = "Changing brightness")

shades has a full set of colour manipulations, including saturation, hue, lightness and opacity (which is similar to scales::alpha).

g + scale_fill_manual(values = saturation(fair_cols, 0.3)) + 
      labs(title = "Dull colours")

You don’t have to set absolute values. Using the delta function, you can change by an absolute amount. Or using the scalefac function, you can scale by a percentage of the current level:

g + scale_fill_manual(values = saturation(fair_cols, delta(-0.2))) + 
      labs(title = "Saturation down by 0.2")

g + scale_fill_manual(values = saturation(fair_cols, scalefac(0.6))) + 
      labs(title = "Saturation down 40%")