【问题标题】:Moving average on several time series using ggplot使用 ggplot 在多个时间序列上移动平均值
【发布时间】:2019-07-01 00:28:22
【问题描述】:

您好,我拼命尝试绘制具有 12 个月移动平均线的多个时间序列。

这是一个具有两个时间序列的花和种子密度的示例。 (我还有更多时间序列要处理……)

#datasets
taxon <- c(rep("Flower",36),rep("Seeds",36))
density <- c(seq(20, 228, length=36),seq(33, 259, length=36))
year <- rep(c(rep("2000",12),rep("2001",12),rep("2002",12)),2)
ymd <- c(rep(seq(ymd('2000-01-01'),ymd('2002-12-01'), by = 'months'),2))

#dataframe
df <- data.frame(taxon, density, year, ymd)

library(forecast)

#create function that does a Symmetric Weighted Moving Average (2x12) of the monthly log density of flowers and seeds 
ma_12 <- function(x) {
  ts_x <- ts(x, freq = 12, start = c(2000, 1), end = c(2002, 12)) # transform to time-series object as it is necessary to run the ma function
  return(ma(log(ts_x + 1), order = 12, centre = T))
}


#trial of the function
ma_12(df[df$taxon=="Flower",]$density)  #works well

library(ggplot2)

#Trying to plot flower and seeds log density as two time series 
ggplot(df,aes(x=year,y=density,colour=factor(taxon),group=factor(taxon))) +
  stat_summary(fun.y = ma_12, geom = "line")  #or geom = "smooth"

#Warning message:
#Computation failed in `stat_summary()`:
#invalid time series parameters specified 

函数 ma_12 工作正常。当我尝试使用 ggplot 绘制时间序列(花和种子)时,问题就来了。我不能将两个分类群都定义为不同的时间序列并对它们应用移动平均线。好像和“stat_summary”有关……

我们非常欢迎任何帮助!提前致谢

注意:以下链接非常有用,但不能直接帮助我,因为我想应用一个特定的函数并根据一个组变量的水平绘制它。目前,我找不到任何解决方案。不管怎样,谢谢你给我这个建议。 Multiple time series in one plot

【问题讨论】:

  • 感谢您的链接,这很有趣。但是,我的问题完全不同,因为我想应用一个特定的函数并根据一个组变量的水平绘制它。目前,我找不到任何类似的主题...
  • 快速选项:ggplot(df, aes(ymd, density, color = factor(taxon))) + geom_smooth(fun.y = ma_12, stat = "summary") 或者只是事先进行计算并正常绘图
  • 同样的问题:“stat_summary() 中的计算失败:指定的时间序列参数无效”。但是,是的,这是一种更快的编码方式,谢谢!

标签: r ggplot2 time-series


【解决方案1】:

这是你需要的吗?

f <- ma_12(df[df$taxon=="Flower", ]$density)
s <- ma_12(df[df$taxon=="Seeds", ]$density)

f <- cbind(f,time(f))
s <- cbind(s,time(s))

serie <- data.frame(rbind(f,s),
                taxon=c(rep("Flower", dim(f)[1]), rep("Seeds", dim(s)[1])))
serie$density <- exp(serie$f)

library(lubridate)
serie$time <- ymd(format(date_decimal(serie$time), "%Y-%m-%d"))

library(ggplot2)
ggplot() + geom_point(data=df, aes(x=ymd, y=density, color=taxon, group=taxon)) +
geom_line(data=serie, aes(x= time, y=density, color=taxon, group=taxon))  

【讨论】:

  • 是的,这个有效!!十分感谢。我将尝试对许多变量进行概括和扩展。
猜你喜欢
  • 2012-10-31
  • 1970-01-01
  • 2014-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-29
  • 2011-03-08
相关资源
最近更新 更多