r - 分组条形图,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 值,这样我就可以在样本中居住在北方的人口比例旁边显示居住在北方的人口在全部人口中的份额.
有什么建议么?
解决方案
您可以按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()
推荐阅读
- html -
等在 Swift String - javascript - CSS - 幻灯片文本背景
- reactjs - 滚动元素时切换状态和 HTML 类 [React, Gatsby]
- typescript - 为什么 Typescript 使用“扩展”这个词来表示泛型而不是“实现”?
- android - 如何检测用户点击 Play 商店内的“打开”以启动我的应用程序?
- javascript - 如何通过值比较合并两个数组 - Google Analytics 和 MongoDB
- visual-studio - 虚幻引擎 4 - TArrays 和 Visual Studio 智能感知问题
- python - 反转链表问题
- c# - C# 偶尔索引 cookie 不保存并在写入后返回原始值
- javascript - 营业时间消失