89_Simple
89_Simple

Reputation: 3805

Cumulative plot using ggplot and dplyr

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

Upvotes: 1

Views: 1277

Answers (1)

Prem
Prem

Reputation: 11955

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

Upvotes: 1

Related Questions