条形图代表各个组的百分比

时间:2020-03-25 03:09:16

标签: r ggplot2 geom-bar

样本数据如下

data = data.frame(group1 = c(1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1),
                  group2 = c(3, 3, 1, 3, 2, 1, 1, 2, 2, 3, 3))

我想创建一个在x轴上具有组1、2、3的条形图,这些条形图代表组中的比例。

例如,

ggplot(data, aes(x = group2, fill = group1))+
geom_bar(position = "dodge") 

我想要的条形图彼此相邻,但仅代表计数,而

ggplot(data, aes(x = group2, fill = group1))+
geom_bar(position = "fill") 

给出了比例,但是它们却是堆叠在一起的-我如何将两者结合在一起以得到比例,但彼此并排显示?

预先感谢

1 个答案:

答案 0 :(得分:0)

我们可以获取按“ group2”分组的百分比,然后绘制

library(dplyr)
library(ggplot2)
data %>% 
    group_by(group2) %>% 
    summarise(group1 = mean(group1)) %>%
    ggplot(aes(x = group2, y = group1)) +
        geom_bar(position = "dodge", stat = 'identity') +
        ylab('percentage')

-输出

enter image description here


或者是相对百分比的另一种选择

ggplot(data, aes(x = group2)) + 
         geom_bar(aes(y = (..count..)/sum(..count..)))+
         ylab('percentage')

-输出

enter image description here

相关问题