R:聚集列 运行 使用 ggplot2 的总计

R: Clustered columns running totals in using ggplot2

我一直在尝试绘制总计 运行 的聚类列。我有两种类型的列,只需要 R 分别计算每个列的 运行 总计。出于某种原因,它将 运行 不同类型的总数加在一起。

library(ggplot2)
df = data.frame(date = c(1, 1, 2, 2, 3, 3),
                val  = c(5, 2, 5, 2, 5, 2),
                type = c("honey","bread","honey","bread","honey","bread"))

ggplot(df, aes(x=date, y=cumsum(val), group = type, fill=type)) +
geom_bar(position = position_dodge(preserve = 'total'), stat="identity") + theme_classic()

我得到:

我要找的是 运行 总计,显示蜂蜜的值为 5,10 和 15,面包的值为 2、4 和 6。

我做错了什么?有什么想法吗?

您可以尝试这样的操作:

library(ggplot2)
library(dplyr)

df1 <- df %>% group_by(type) %>% mutate(N=cumsum(val))

ggplot(df1,aes(x=date, y=N, group = type, fill=type)) +
  geom_bar(position = position_dodge(preserve = 'total'), stat="identity") + theme_classic()

给出:

我宁愿在 ggplot 中进行计算,但在外部计算 cumsum()

这是我的建议:

library(ggplot2)
library(dplyr)

df %>% 
  group_by(type) %>% 
  mutate(total = cumsum(val)) %>% 
  ggplot(aes(x = date, y = total, fill = type)) +
  geom_bar(position = position_dodge(preserve = 'total'), stat="identity") + 
  theme_classic()

... 这给你输出:

另一个解决方案

ggplot(df, aes(x=date, y=ave(x = val, type, FUN = cumsum), group = type, fill=type)) +
  geom_bar(position = position_dodge(preserve = 'total'), stat="identity") + theme_classic()