r - 如何将百分比限制在每个单独的方面而不是跨方面?
问题描述
R 的新手,所以我的代码可能不会尽可能高效。
每个方面代表一个不同的研讨会。研讨会的参与者对研讨会进行了评价。目前,每个研讨会的每个评级(例如,“有帮助”、“没有帮助”等)的百分比正在计算为所有研讨会的百分比。换言之,图表显示,在所有四场研讨会中,约 16% 的受访者认为“管理您的非营利组织”研讨会“非常有帮助”。
但是,我需要它来限制对单个研讨会的评分(即,图表应显示 100% 的参加“管理您的非营利组织”研讨会的受访者将其评为“非常有帮助”。
下面是我的代码。我认为问题可能与geom_bar(aes(y=(..count..)/sum(..count..))
,但不确定。在现有方法中制作我想要的图表的最简洁方法是什么?
webinar_rating_graph <- response_master_df %>%
ggplot(aes(x=`How would you rate the content of the webinar?`)) +
facet_grid(cols=vars(str_wrap(Webinar, 15))) +
geom_bar(aes(y=(..count..)/sum(..count..)),
fill="skyblue", color="black") +
labs(title="Ratings of Webinars as Percentage of Respondants", y="Percentage of Respondants") +
theme(
plot.title = element_text(hjust = 0.5, size=12),
strip.text=element_text(hjust=.5, size=8),
axis.text=element_text(hjust=.5, size=5),
axis.title=element_text(size=8)) +
scale_y_continuous(labels=scales::percent) +
scale_x_discrete(
labels=scales::wrap_format(4),
limits = c("Very Helpful", "Somewhat Helpful",
"Neither Helpful nor Unhelpful",
"Somewhat Unhelpful", "Very Unhelpful"))
webinar_rating_graph
这是结果图:
解决方案
正如@stefan 评论的那样,您可以总结 ggplot 之外的数据,然后绘制计算的百分比。这通常会给您最大的灵活性(请参阅本答案末尾的示例)。
要在 ggplot 中执行所有操作,您可以使用内部计算的变量..prop..
来计算百分比。我们还需要将group
美学设置为按构面变量分组,以确保在每个面板中计算百分比,而不是在所有面板中计算。
这是一个使用内置mtcars
数据框的示例。我们按列分面vs
,因此我们使用group=vs
withingeom_bar
来确保在每个分vs
面内计算百分比:
library(tidyverse)
mtcars %>%
ggplot(aes(factor(cyl))) +
geom_bar(aes(y=..prop.., group=vs)) +
facet_grid(cols=vars(vs)) +
scale_y_continuous(label=scales::percent, limits=c(0,1), expand=c(0,0)) +
theme_bw()
如果要预先汇总数据,可以这样做:
mtcars %>%
# Get counts of each group
group_by(vs, cyl) %>%
tally %>%
# Get percent within each level of vs
group_by(vs) %>%
mutate(pct = n/sum(n)) %>%
ggplot(aes(cyl, pct)) +
geom_col() +
facet_grid(cols=vars(vs)) +
scale_y_continuous(label=scales::percent, limits=c(0,1), expand=c(0,0)) +
theme_bw()
推荐阅读
- unit-testing - JEST 单元测试用例 - 初学者和面临的问题
- javascript - 如何在网站 js 中读取带有换行符的 docx?
- python - 剪切自动编码器的一部分(pytorch)
- css - Github 页面上的媒体查询不适用
- azure - 在 Azure Functions 中使用颜色记录信息
- python - 奥多。如何将 char 字段迁移到同一模型中的 many2many
- annotations - 如何将带注释的 VCF 文件转换为 MAF?
- deep-learning - “在 PyTorch 中,默认情况下如何初始化层权重和偏差?”的后续行动
- powershell - 使用 Powershell 合并两个 CSV 文件
- pulseaudio - 临时流的体积