首页 > 解决方案 > 代表各个组百分比的条形图

问题描述

样本数据如下

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") 

给出了比例,但它们是堆叠的 - 我如何将两者结合起来以获得比例,但彼此相邻显示?

提前致谢

标签: rggplot2geom-bar

解决方案


我们可以得到按“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')

-输出

在此处输入图像描述


或者另一个选项,如果它是相对百分比

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

-输出

在此处输入图像描述


推荐阅读