【问题标题】:Cumulative plot in ggplot2ggplot2中的累积图
【发布时间】:2018-03-12 15:27:30
【问题描述】:

样本数据

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

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

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

这里出了什么问题?

【问题讨论】:

标签: r plot ggplot2 cumsum


【解决方案1】:

问题在于,当您在美学中使用 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() 

【讨论】:

    【解决方案2】:

    你的 cumsum 不是每年都在这里

    使用 data.table 你可以做到

    library(data.table)
    dat <- setDT(dat)
    dat[,cumulsum :=cumsum(value), by = year]
      ggplot(, aes(x = id.2wk, y = cumulsum, colour = factor(year))) + 
      geom_line(size = 1)+
      geom_point() 
    

    【讨论】:

      猜你喜欢
      • 2013-08-23
      • 2013-03-28
      • 1970-01-01
      • 1970-01-01
      • 2021-05-10
      • 2021-05-04
      • 1970-01-01
      • 2014-06-21
      • 2021-05-12
      相关资源
      最近更新 更多