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!
Asked
Active
Viewed 176 times
0

Giuseppe D'alterio
- 200
- 3
- 9
-
1You 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 Answers
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.
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.
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)

Nirshad Nijam
- 182
- 5
-
Thank you, but I should keep my `scale_fill_discrete`. Using `scale_fill_manual` would substitute my current options – Giuseppe D'alterio Aug 31 '21 at 13:31