按变量分组的条形图最多可计入100%

时间:2017-10-19 21:12:26

标签: r

我试图得到一个按照'阶段'分组的条形图。每个阶段的百分比应为100%,因此总计为200%。我尝试了很多东西,但我没有成功。看过其他问题但是使用了非常不同的数据。如果有人可以帮助我,这对我有帮助。

BEAdata %>% 
  count(Phase = factor(Phase), Activities = factor(Activities)) %>% 
  mutate(pct = prop.table(n) * 100) %>% 
  ggplot(aes(x = Phase, y = n, fill = Activities)) + 
    geom_bar(stat = 'identity', position = 'dodge') + 
    geom_text(aes(y = n + .2,    # nudge above top of bar
              label = paste0(round(pct, 2), '%')),    # prettify
              position = position_dodge(width = .9), 
              size = 3)

Output

Data

1 个答案:

答案 0 :(得分:0)

在进行prop.table()计算之前,您只需要添加一个组。

唯一的变化是group_by(Phase)行。

require(dplyr)
require(ggplot2)

BEAdata %>% 
  count(Phase = factor(Phase), Activities = factor(Activities)) %>% 
  group_by(Phase) %>%
  mutate(pct = prop.table(n) * 100) %>% 
  ggplot(aes(x = Phase, y = n, fill = Activities)) + 
    geom_bar(stat = 'identity', position = 'dodge') + 
    geom_text(aes(y = n + .2,    # nudge above top of bar
              label = paste0(round(pct, 2), '%')),    # prettify
              position = position_dodge(width = .9), 
              size = 3)