创建具有闪避位置的比例条形图

时间:2019-02-20 11:52:00

标签: r ggplot2 bar-chart

我正在尝试创建以下图,但在y轴上具有比例

library(ggplot2)
ggplot(data = diamonds) + 
  geom_bar(mapping = aes(x = cut, fill = clarity), position = "dodge")

但是当我添加y=..prop..时,它不会按clarity进行分组。我尝试了以下方法:

ggplot(data = diamonds) + 
      geom_bar(mapping = aes(x = cut, y = ..prop.., fill = clarity), position = "dodge")

1 个答案:

答案 0 :(得分:4)

要计算比例(或频率),您可以使用..count..(比例是特定的count除以所有count' s):

library(ggplot2)
ggplot(diamonds, aes(cut, (..count..) / sum(..count..), fill = clarity)) +
    geom_bar(position = "dodge") 

enter image description here