How do I change the color of my bar plot using ggplot2 package of R?

Viewed 65

I am practicing to create a bar chart using the following data frame and packages -

library(ggplot2)
library(RColorBrewer)

df = data.frame (Bacteria = c("Acinetobacter", 
                          "Citrobacter", 
                          "Enterobacter", 
                          "Eschwerichia coli",
                          "Klebsiella",
                          "Proteus",
                          "Pseudomonas aeruginosa",
                          "Serratia"),
             Count = c(82,32,55,193, 110,58,200,8),
             Percentage = c(11.1, 4.3, 7.5, 26.2, 14.9, 7.9, 27.1, 1.1))

p1 = ggplot (data = df, aes(x = Percentage, y = Bacteria))+ 
geom_bar(stat = "identity")

enter image description here

So, now I want to add some colors to my plot and I tried RColorBrewerpackage.

p1++scale_color_brewer(palette="Set3")

but no color has changed at all. What am I doing wrong here?

1 Answers

If you want to add some filling, you should add a fill argument into your aes.

Something like that should work:

library(ggplot2)
library(RColorBrewer)

ggplot (data = df, aes(y = Percentage, x = Bacteria, fill = Bacteria))+ 
  geom_col()+
  scale_color_brewer(palette="Set3")

enter image description here

Does this answer your question ?


NB: Please note that geom_bar(stat = "identity") is exactly the same that geom_col()

Related