代码之家  ›  专栏  ›  技术社区  ›  Nishant

如何自动迭代绘图。使用ggplot的arima预测

  •  1
  • Nishant  · 技术社区  · 7 年前

    我有以下数据:

    df
    
       repo revrepo bankrate  CRR Callrate
    1  9.00    6.75      7.0 8.00     7.49
    2  8.75    6.50      7.0 7.50     8.03
    3  8.50    6.50      7.0 7.50     7.24
    4  8.50    6.50      7.0 7.50     7.19
    5  8.50    6.50      7.0 7.50     6.94
    6  8.50    6.50      7.0 7.50     7.30
    7  8.50    6.50      6.5 7.50     7.40
    8  8.50    6.50      6.5 5.75     6.97
    9  8.50    6.50      6.5 5.50     7.08
    10 8.50    6.50      6.5 5.50     6.63
    11 8.50    6.50      6.5 5.50     6.73
    12 8.00    6.00      6.5 5.50     6.97
    13 8.00    6.00      6.5 5.50     6.58
    14 8.00    6.00      6.5 5.50     6.90
    15 8.00    5.75      6.5 5.00     6.04
    

    我正在迭代绘制ts,如下所示:

    y=df
    colnames <- dimnames(y)[[2]]
    
    (plots<-lapply(df,function(x) autoplot(fit<-forecast(auto.arima(ts(x,start=c(2001,4),end = c(2002,6),frequency = 12))))+labs(x = 'Time', y = paste(colnames[i])) + ggtitle(paste(colnames[i],'over Time'))+  theme(plot.title = element_text(hjust = 0.5)) +
    yaztheme::theme_yaz() ))
    

    我没有得到情节的正确标题。显示其中一个图以供参考:

    enter image description here

    是否有更好的方法来进行迭代时间序列预测和预测绘图。

    1 回复  |  直到 7 年前
        1
  •  2
  •   akrun    7 年前

    如果我们需要相应的列名,请遍历列的序列

    lst <- lapply(seq_along(df),function(i) {
    autoplot(fit<-forecast(auto.arima(ts(df[[i]],start=c(2001,4),
                    end = c(2002,6),frequency = 12))))+
             labs(x = 'Time', y = paste(colnames[i])) +
             ggtitle(paste(colnames[i],'over Time'))+ 
             theme(plot.title = element_text(hjust = 0.5))
      } 
    )
    
    lst[[5]]
    

    enter image description here


    或与 for

    lst <- vector('list', length(df))
    for(i in seq_along(df)) {
      lst[[i]] <- autoplot(forecast(auto.arima(ts(df[[i]],
                 start=c(2001,4),end = c(2002,6),frequency = 12))))+
               labs(x = 'Time', y = paste(colnames[i])) +
               gtitle(paste(colnames[i],'over Time'))+ 
               theme(plot.title = element_text(hjust = 0.5))
    
    }