首页 > 解决方案 > 分组条形图,ggplot中的样本与总体

问题描述

我想制作一个分组条形图,在其中比较人口中地区人口的百分比分布与样本中的分布。

代码如下所示:

library(dplyr)
library(ggplot2)

df <- tibble(in_sample= c('yes', 'no', 'no', 'no', 'yes', 'yes', 'no', 'no', 'no', 'yes', 'no', 'yes', 
                          'no', 'no', 'no', 'yes', 'yes', 'no', 'yes', 'yes', 'no', 'yes', 'yes', 'no',
                          'yes', 'no', 'yes', 'no' , 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'yes', 
                          'no', 'no', 'no', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'yes', 'no', 
                          'yes', 'yes', 'no', 'yes', 'yes', 'no', 'yes', 'no', 'yes', 'no' , 'yes', 'no'),
             region = c('West','East', 'South', 'North', 'West', 'East',
                            'South', 'North', 'South', 'West', 'South', 'West',
                            'East', 'South', 'East', 'East', 'East', 'East',
                            'North', 'East', 'South', 'West', 'West', 'East',
                            'North', 'North', 'East', 'South', 'West', 'West',
                            'West','West', 'South', 'West', 'West', 'West',
                            'West', 'West', 'West', 'West', 'North', 'North',
                            'North', 'North', 'South', 'North', 'East', 'North',
                            'North', 'North', 'South', 'North', 'North', 'North',
                            'South', 'South', 'South', 'South', 'North', 'North'))

现在,我有一个看起来像这样的解决方案:

  ggplot(data = df) +
  geom_bar(mapping = aes(x = region, y = ..prop.., group = 1), stat = "count") +
  scale_y_continuous(breaks = seq(0, .4, .05), labels = scales::label_percent(accuracy = 1)) +
  facet_wrap(~in_sample, labeller = labeller(in_sample = c("no" = "Population", "yes" = "Sample"))) +
  theme_bw()

但我希望将这些区域彼此相邻分组并填写 in_sample 值,这样我就可以在样本中居住在北方的人口比例旁边显示居住在北方的人口在全部人口中的份额.

有什么建议么?

标签: rggplot2

解决方案


您可以按in_sample对条形图进行分组并使用position_dodge(). 这是你想要的吗?

ggplot(data = df) +
  geom_bar(mapping = aes(x = region, y = ..prop.., group = in_sample, fill = in_sample), 
           stat = "count", position = position_dodge()) +
  scale_y_continuous(breaks = seq(0, .4, .05), labels = scales::label_percent(accuracy = 1)) +
  scale_fill_manual(values = c("blue", "red"), labels = c("Population", "Sample"), name = "")+
  theme_bw()

在此处输入图像描述


推荐阅读