添加图例并在分组条形图上更改颜色

时间:2017-11-13 13:30:15

标签: r ggplot2 colors legend geom-bar

我创建了这样的情节;

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

现在我想为变量" color"添加一个图例,我也想更改条形的颜色。图表正是我想要的样子,如果可能的话,我不想改变数据集的结构,只需添加图例并更改颜色。

我找不到适合这种"百分比"风格图形的示例。

1 个答案:

答案 0 :(得分:0)

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