ggplot2 中的累积图

89_*_*ple 1 plot r ggplot2 cumsum

样本数据

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

with(dat, plot(id.2wk[year == 2012], cumsum(value[year == 2012]), type = "b"))
with(dat, points(id.2wk[year == 2013], cumsum(value[year == 2013]), type = "b"))
with(dat, points(id.2wk[year == 2014], cumsum(value[year == 2014]), type = "b"))
with(dat, points(id.2wk[year == 2015], cumsum(value[year == 2015]), type = "b"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我想使用 ggplot2 创建相同的图。我这样做了:

  ggplot(dat, aes(x = id.2wk, y = cumsum(value), colour = factor(year))) + 
  geom_line(size = 1)+
  geom_point() 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

这里出了什么问题?

MrF*_*ick 6

问题在于,当您cumsum()在美学中使用时,它适用于所有值,而不仅仅是特定年份内的值。

与使用 进行转换相比,先使用 进行转换,然后绘制结果ggplot会更安全。dplyr例如

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

在此输入图像描述