Search code examples
rggplot2color-palette

How to use custom color palette with ggplot2 in R?


I am trying to create a custom color palette using hex codes and use it for the "fill" aesthetic (discrete variable) for geom_bar.

Please see code below.

library(pacman)
p_load(tidyverse, ggplot2, RColorBrewer)

palette_new <- colorRampPalette(colors = c("white", "#154360", "#FF5733", "#FFC300", "#1ABC9C"))(5)
scales::show_col(palette)

Plot:

data(diamonds)

ggplot(diamonds, aes(x = color, fill = cut)) +
  geom_bar() +
  scale_fill_brewer(palette = "palette_new")

Output, but see error message below: Output

Warning message: In pal_name(palette, type) : Unknown palette palette_new

I have seen several questions about this on stack overflow and have tried different things that do not work. Thank you in advance!


Solution

  • I think that your main problem is that RColorBrewer only let's you use it's pre-defined palettes. So your palette with the values you picked will actually look like this:

    enter image description here

    And both @akrun and @Specer are correct, if you use

    
    palette_new <- grDevices::colorRampPalette(
              colors = c("white", "#154360", "#FF5733", "#FFC300", "#1ABC9C"))(5)
    ggplot(diamonds, aes(x = color, fill = cut)) +
      geom_bar() +
      scale_fill_manual(values = palette_new)
    

    you should get a plot like this: enter image description here

    You will get this: