使用ggplot和dplyr的累积图

时间:2018-05-22 12:52:06

标签: r ggplot2 dplyr

示例数据:

dat <- data.frame(year = as.factor(rep(c(2012:2015),each = 6)),id.2wk = rep(c(18,19,20,21,22,23),times = 4), 
              value = c(1.8,15.6,32.9,27.5,19.6,2.6,1,8,42,35,11,3,2,7,12,47,26,7,2,13,24,46,12,4))

ggplot(dat %>% group_by(year) %>% mutate(cv=cumsum(value)), 
aes(x = id.2wk, y = cv, colour = factor(year))) + 
geom_line(size = 1)+
geom_point() 

packageVersion("ggplot2")
2.2.1

enter image description here

我期待一个类似于下面的情节。什么地方出了错?

enter image description here

1 个答案:

答案 0 :(得分:1)

如何使用data.table来计算群组内的累积总和?

library(data.table)
library(ggplot2)

ggplot(setDT(dat)[, cv:= cumsum(value), year], 
       aes(x = id.2wk, y = cv, colour = factor(year))) + 
  geom_line(size = 1) +
  geom_point() 

示例数据:

dat <- data.frame(year = as.factor(rep(c(2012:2015),each = 6)),
                  id.2wk = rep(c(18,19,20,21,22,23),times = 4), 
                  value = c(1.8,15.6,32.9,27.5,19.6,2.6,1,8,42,35,11,3,2,7,12,47,26,7,2,13,24,46,12,4))