如何使用ggplot迭代绘制auto.arima预测

时间:2018-02-05 12:18:24

标签: r ggplot2 time-series forecasting

我有以下数据:

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 个答案:

答案 0 :(得分:2)

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

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

}