【问题标题】:combine time series plot by using R使用 R 组合时间序列图
【发布时间】:2013-02-04 17:26:52
【问题描述】:

我想在一张图上组合三个图形。来自 R 内部的数据,即“nottem”。有人可以帮助我编写代码以使用不同的颜色将季节性均值和谐波(余弦模型)及其时间序列图放在一起吗?我已经写了模型代码只是不知道如何将它们组合在一起进行比较。

Code :library(TSA)
  nottem
  month.=season(nottem)
  model=lm(nottem~month.-1)
  summary(nottem)
  har.=harmonic(nottem,1)
  model1=lm(nottem~har.)
  summary(model1)
plot(nottem,type="l",ylab="Average monthly temperature at Nottingham castle") 
points(y=nottem,x=time(nottem), pch=as.vector(season(nottem)))

【问题讨论】:

    标签: time-series


    【解决方案1】:

    只需将您的时间序列放入矩阵中:

    x = cbind(serie1 = ts(cumsum(rnorm(100)), freq = 12, start = c(2013, 2)),
    serie2 = ts(cumsum(rnorm(100)), freq = 12, start = c(2013, 2)))
    
    plot(x)
    

    或者配置绘图区域:

    par(mfrow = c(2, 1)) # 2 rows, 1 column
    serie1 = ts(cumsum(rnorm(100)), freq = 12, start = c(2013, 2))
    serie2 = ts(cumsum(rnorm(100)), freq = 12, start = c(2013, 2))
    
    require(zoo) 
    plot(serie1)
    lines(rollapply(serie1, width = 10, FUN = mean), col = 'red')
    plot(serie2)
    lines(rollapply(serie2, width = 10, FUN = mean), col = 'blue')
    

    希望对你有帮助。

    PS.:本例不需要zoo包,可以使用filter功能。 您可以使用以下方法提取季节性平均值

    s.mean = tapply(serie, cycle(serie), mean)
    # January, assuming serie is monthly data
    print(s.mean[1])
    

    【讨论】:

      【解决方案2】:

      此图很难阅读,因为您的三组值非常相似。不过,如果您只想在样本图上绘制所有这些图形,您可以使用模型生成的系数轻松完成。

      第 1 步:绘制原始数据。这来自您的原始代码。

      plot(nottem,type="l",ylab="Average monthly temperature at Nottingham castle") 
      

      第 2 步:为均值图和余弦图设置 x 值。

      x <- seq(1920, (1940 - 1/12), by=1/12)
      

      第 3 步:通过重复第一个模型的系数来绘制季节性均值。

      lines(x=x, y=rep(model$coefficients, 20), col="blue")
      

      第 4 步:使用第二个模型的系数计算余弦函数的 y 值,然后绘图。

      y <- model1$coefficients[2] * cos(2 * pi * x) + model1$coefficients[1]
      lines(x=x, y=y, col="red")
      

      ggplot 变体:如果您决定为您的绘图切换到流行的“ggplot2”包,您可以这样做:

      x <- seq(1920, (1940 - 1/12), by=1/12)
      y.seas.mean <- rep(model$coefficients, 20)
      y.har.cos <- model1$coefficients[2] * cos(2 * pi * x) + model1$coefficients[1]
      
      plot_Data <- melt(data.frame(x=x, temp=nottem, seas.mean=y.seas.mean, har.cos=y.har.cos), id="x")
      ggplot(plot_Data, aes(x=x, y=value, col=variable)) + geom_line()
      

      【讨论】:

        猜你喜欢
        • 2018-10-22
        • 2016-05-11
        • 1970-01-01
        • 2016-02-17
        • 1970-01-01
        • 1970-01-01
        • 2020-04-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多