首页 > 解决方案 > 如何将百分比限制在每个单独的方面而不是跨方面?

问题描述

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

这是结果图:

1

标签: rggplot2

解决方案


正如@stefan 评论的那样,您可以总结 ggplot 之外的数据,然后绘制计算的百分比。这通常会给您最大的灵活性(请参阅本答案末尾的示例)。

要在 ggplot 中执行所有操作,您可以使用内部计算的变量..prop..来计算百分比。我们还需要将group美学设置为按构面变量分组,以确保每个面板中计算百分比,而不是在所有面板中计算。

这是一个使用内置mtcars数据框的示例。我们按列分面vs,因此我们使用group=vswithingeom_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()

推荐阅读