0

I am trying to manually change the colors of a barplot based on a grouping variable. In order to properly order my values, I have to use the scale_fill_discrete() function, so that I cannot apply a scale_fill_manual() function (if more information is needed please leave a comment). My question is: do you know if it is possible to set a color this way? Thank you in advance!

  • 1
    You should be able to order your values in any way you want using factors, and then apply a `scale_fill_manual()`. Please provide code so that we can reproduce your problem. https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – qdread Aug 31 '21 at 11:52

1 Answers1

1

Using scale_fill_manual() wouldn't be a problem. Because, it will override the previous colour scale you've used. I used an existing dataset to suit your problem.

ggplot(mpg, aes(displ, fill = drv)) +
geom_bar() 

This would create a plot like this. first plot without customization

If you want to customize, you can do this

ggplot(mpg, aes(displ, fill = drv)) +
geom_bar() + 
scale_fill_manual(values=c("red", "black", "green"))

The above code will output this. w/customizing

If you want further control over your palettes, you can do this.

myColors <- c("4"="red", "f"="yellow", "r"="blue")
#myColors is a named vector
ggplot(mpg, aes(displ, fill = drv)) +
geom_bar() + scale_fill_manual(values=myColors)

This will give you this: fully-controlled