Search code examples
rggplot2colorslegendgeom-bar

Add Legend and change Colour on grouped bar plot


I created a plot like this;

library("ggplot2")    
ggplot(data = diamonds) + 
      geom_bar(mapping = aes(x = color, y = ..prop.., group = 2)) + 
      scale_y_continuous(labels=scales::percent) +
      facet_grid(~cut)

Now I want to add a legend for the variable "color", also I want to change the colour of the bars. The graph is exactly how I want it to be, and if possible I don't want change the structure of the dataset, just add a legend and change colours.

I could not find example that fit for this "percentage"-style graphics.


Solution

  • ggplot(data = diamonds, aes(x = color, y = ..prop.., group = cut)) + 
      geom_bar(aes(fill = factor(..x.., labels = LETTERS[seq(from = 4, to = 10 )]))) + 
      labs(fill = "color") + 
      scale_y_continuous(labels = scales::percent) + 
      facet_grid(~ cut)
    

    enter image description here