【问题标题】:Sum only values from group inside ggplot function仅对 ggplot 函数内的组中的值求和
【发布时间】:2019-09-18 13:41:54
【问题描述】:

ggplot 中是否有办法仅对我选择的组中的值求和?

我有这个data.frame

      table age       n
1      base   0     122
2      base   1   20043
3      base   2 1057146
4      base   3 1787504
5      base   4 2211046
6  sample_1   1      50
7  sample_1   2    2478
8  sample_1   3    4186
9  sample_1   4    5161
10 sample_2   1      41
11 sample_2   2    2492
12 sample_2   3    4351
13 sample_2   4    5288

我想在每个表(列表)中按年龄绘制比例。我试图在 ggplot 函数中对列 n 求和,但它对所有表中的值求和:

df  %>% 
  ggplot(aes(x = age, y = n/sum(n), group = table)) +
  geom_bar(stat = 'identity') +
  facet_grid(. ~ table)

我找到的解决方案是在制作情节之前处理桌子:

df %>% group_by(table) %>% mutate(prop = n/sum(n)) %>% 
  ggplot(aes(x = age, y = prop, group = table)) +
  geom_bar(stat = 'identity') +
  facet_grid(. ~ table)

可以直接在ggplot函数中做吗?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    y 设置为比例,并可选择将比例标签设置为percent

    library(ggplot2)
    library(scales)
    
    ggplot(df, aes(x = age, y = ave(n, table, FUN = prop.table), group = table)) +  
            geom_bar(stat = "identity") + 
            scale_y_continuous(labels = percent) +
            facet_grid(. ~ table) +
            ylab("percent")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-29
      • 1970-01-01
      • 1970-01-01
      • 2022-07-20
      • 2016-09-05
      • 1970-01-01
      • 1970-01-01
      • 2022-11-19
      相关资源
      最近更新 更多