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

问题描述 投票:0回答:1

示例数据如下

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

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

提前感谢

r ggplot2 geom-bar
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.