1

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

11
  • 2
    The plot seems to be working in my system, I am not sure what happened at your end. Commented May 22, 2018 at 12:58
  • Is it related to ggplot version I am using? Could you share which version are you using? Commented May 22, 2018 at 12:59
  • It works well and under the same ggplot2 version (2.2.1) Commented May 22, 2018 at 12:59
  • ‘2.2.1.9000’ This my ggplot version, github.com/tidyverse/ggplot2/blob/master/NEWS.md Commented May 22, 2018 at 12:59
  • 1
    I'm thinking about packages conflicts(?) Commented May 22, 2018 at 13:05

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.