在ggplot2中为geom bars指定颜色

时间:2018-05-26 11:14:53

标签: r ggplot2 colors bar-chart geom-bar

我的数据框如下

   School Gender Value ColorGroup
1 School1   Male    10      1Male
2 School1 Female    30    1Female
3 School2   Male    40      1Male
4 School2 Female    70    1Female
5 School3   Male     5      2Male
6 School3 Female    90    2Female

我可以创建以下条形图

ggplot(data=data2, aes(x=School, y=Value, group = Gender, fill = Gender)) + 
  geom_bar(stat = "identity", position = position_dodge(), width =  0.5)

ggplot(data=data2, aes(x=School, y=Value, group = Gender, fill = ColorGroup)) + 
  geom_bar(stat = "identity", position = position_dodge(), width =  0.5)
  1. 条形图1 - 按性别分组 enter image description here
  2. 条形图2 - 按ColorGroup分组 enter image description here
  3. 我想要做的是指定颜色如下 School3使用以下代码与School1和School2有不同的颜色

    cols33 <- c("1Male" = "yellow", "1Female" = "orange", "2Male" = "red", "2Female" = "blue") 
    
    ggplot(data=data2, aes(x=School, y=Value, group = Gender,fill = ColorGroup)) + 
      geom_bar(stat = "identity", position = position_dodge(), width =  0.5) + 
      scale_color_manual(name="",values=cols33)
    

    但我仍然得到与barchart2相同的输出。 enter image description here

    请帮助您理解为什么我的代码中没有遵守scale_color_manual。

1 个答案:

答案 0 :(得分:0)

我在aes中绘制了填充颜色。因此,需要使用scale_fill_manual,而不是scale_color_manual。