【问题标题】:Changing a bar plot in ggplot2 from counts to proportions based on facets [duplicate]将ggplot2中的条形图从计数更改为基于方面的比例[重复]
【发布时间】:2016-12-06 01:32:06
【问题描述】:

我用过这段代码:

data %>% 
gather(activity, ct, ActSwim:acteat) %>% 
filter(ct == 1) %>% 
count(activity, Location) %>% 
ggplot(., aes(activity, n)) +
geom_barplot(stat = "identity") + 
facet_wrap(~Location, ncol = 1)

创建这个

如何将这个从计数更改为比例,以说明在每个地点接受调查的人数不同这一事实?我希望比例能够反映每个方面的比例(在本例中为位置)。

【问题讨论】:

  • 请提供数据(虚拟或实际)以获得完全可重现的示例。

标签: r ggplot2 dplyr


【解决方案1】:

尽管这可能是重复的,但您有两个选择。

  1. ggplot 为您进行转换。
  2. 自己汇总数据并传递给ggplot

我订阅了 #2,因为从长远来看,它提供了更多的灵活性。

library(dplyr)
library(ggplot2)
library(scales)

data %>% 
  gather(activity, ct, ActSwim:acteat) %>% 
  filter(ct == 1) %>% 
  count(activity, Location) %>% 
  group_by(activity) %>%
  mutate(percentage = n/sum(n)) %>%
  ggplot(., aes(activity, percent)) +
  geom_col() + 
  facet_wrap(~Location, ncol = 1) +
  scale_y_continuous(labels = percent)

【讨论】:

  • 我尝试使用此代码,但出现“data.frame 错误(x = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L , : 参数暗示不同的行数:33, 0".
  • 为了清楚起见,我希望最终图表显示每个方面内的比例。所以这个问题与所链接的内容不重复。
  • 意识到我使用 summarize 而不是 mutate 希望现在可以使用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-06
  • 2021-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-26
  • 2016-07-07
相关资源
最近更新 更多