Search code examples
rggplot2bar-chartdata-visualizationcolorbrewer

How to plot a dataset containing counts using ggplot and brewer package?


Following is my dataset

feature_user <- data.frame (Features = c("Battery","Build_Design", "Camera","Connectivity","Delivery", 
                                         "Design", "Display", "Gaming_Experience", "Performance", 
                                         "Post_Usage", "Protection", "Recommendation", "Sound", "Value_Money"), 
                            Users = c(852, 89, 471, 96, 228, 143, 131, 18, 379, 354, 35, 271, 99, 510))

I'm trying to bar plot the data using the following code

library(ggplot2)

ggplot(feature_user, aes(x = reorder(Features, Users), y = Users)) + 
  geom_bar(stat = "identity", position = "dodge") + 
  scale_fill_brewer(palette = "Set1") + 
  coord_flip() + 
  ggtitle("Most Talked Feature by Users") +
  ylab("No of Users") + 
  xlab("Features") 

But the problem is, I'm not getting the output as per the color code mentioned in scale_fill_brewer. Instead I get plain grey bar plots. I'm not sure what is the issue. Kindly help


Solution

  • You need to add fill inside the aes of your geom

    library(ggplot2)      
    
    ggplot(feature_user,aes(x=reorder(Features,Users),y=Users)) + 
      geom_col(stat='identity', aes(fill=Features), width=.5)+
      coord_flip() +
      ggtitle("Most Talked Feature by Users") +ylab("No of Users") + xlab("Features")
    

    The result is

    enter image description here

    But, by adding:

    scale_fill_brewer(palette = "Set1") +
    

    it messes with the result. and some columns do not present.