1
votes

Sample data:

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

I was expecting a plot similar to below. What went wrong?

enter image description here

1
The plot seems to be working in my system, I am not sure what happened at your end.PKumar
Is it related to ggplot version I am using? Could you share which version are you using?89_Simple
It works well and under the same ggplot2 version (2.2.1)DJV
‘2.2.1.9000’ This my ggplot version, github.com/tidyverse/ggplot2/blob/master/NEWS.mdPKumar
I'm thinking about packages conflicts(?)DJV

1 Answers

1
votes

How about using data.table to calculate cumulative sum within group?

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() 

Sample data:

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))