Search code examples
rggplot2plotcolors

Custom color palette for scale_fill_fermenter()


I'm using ggplot2's scale_fill_fermenter() for a discrete colorbar legend. Colors can be specified under the palette argument, however only a limited set of color palettes seem to be available (those from RColorBrewer::display.brewer.all()).

Is there a way to define a custom color palette? The trivial solution of passing a vector of color names/hex does not work ...

Cheers!


Solution

  • scale_fill_fermenter is a wrapper which returns

    binned_scale(aesthetics, "fermenter", 
      binned_pal(brewer_pal(type, palette, direction)), 
      na.value = na.value, guide = guide, ...)
    

    If it's fine for you to call the non-exported function ggplot2:::binned_pal you can use this code as a template to write a custom scale_fill_fermenter function which allows for custom color palettes and may look like so:

    library(ggplot2)
    
    v <- ggplot(faithfuld) +
      geom_tile(aes(waiting, eruptions, fill = density))
    
    # Custom palette
    pal <- scales::hue_pal()(8)
    
    scale_fill_fermenter_custom <- function(pal, na.value = "grey50", guide = "coloursteps", aesthetics = "fill", ...) {
      binned_scale("fill", "fermenter", ggplot2:::binned_pal(scales::manual_pal(unname(pal))), na.value = na.value, guide = guide, ...)  
    }
    
    v + scale_fill_fermenter_custom(pal)