Omit Brighter colors on RColorBrewer palette to use in ggplot2

Viewed 2813

I'd like to use the darker colors in the "Oranges" palette in RColorBrewer to use in my ggplot (bargraph). I however am unable to. Help. Below is the sample code:

my_palette = brewer.pal(n = 9, "Oranges")[4:9]


### Bar Plots ###
ggplot(Sample_df, aes(x = Sample_Score), fill = Sample_Score) + 
  geom_bar(stat = "count", width = 0.8) + scale_fill_brewer(palette= my_palette)  + scale_y_log10(labels = comma) +
   labs(title="Distribution of customers according to Sample Score",x="Sample Score", y="Number of Customers") +
     theme(plot.title = element_text(face = "bold", size = 10),
        axis.title.x = element_text(face = "bold", size = 8),  
        axis.title.y = element_text(face = "bold", size = 8), legend.position="none")
1 Answers

This is because you are using scale_fill_brewer(). This command expects an RColorBrewer palette name. (e.g. "Oranges"). It cannot read your custom palette name my_palette Instead, use scale_fill_manual()

I created an own reproducible example:

library(RColorBrewer)
library(ggplot)

set.seed(1234)
df <- data.frame(x=runif(10,0,1), y=runif(10,0,1), c=factor(sample(1:5,10,replace=T)))

ggplot(data=df, aes(x=x,y=y)) + geom_point(aes(color=c)) + scale_color_brewer(palette = 'Oranges')

As you can see, I am calling the RColorBrewer palette "Oranges". As you mentioned, these coloured are very light, and you may want to use only the darker ones. To do this, you can make a custom palette and call it using scale_color_manual() (or scale_fill_manual() in your case) instead of scale_color_brewer().

my_palette <- brewer.pal(name="Oranges",n=9)[4:9]

ggplot(data=df, aes(x=x,y=y)) + geom_point(aes(color=c)) + scale_color_manual(values = my_palette)

This will now use the colors you specified in my_palette

Related