【发布时间】: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函数中做吗?
【问题讨论】: