带有x轴的绘图包含日期

时间:2013-06-15 07:17:26

标签: r forecasting

我使用以下数据加载数据框(命名为stock):

day               value
2000-12-01 00:00:00 11.809242 
2000-12-01 06:00:00 10.919792 
2000-12-01 12:00:00 13.265208 
2000-12-01 18:00:00 13.005139 
2000-12-02 00:00:00 10.592222  
2000-12-02 06:00:00 8.873160 
2000-12-02 12:00:00 12.292847 
2000-12-02 18:00:00 12.609722 
2000-12-03 00:00:00 11.378299 
2000-12-03 06:00:00 10.510972  
2000-12-03 12:00:00 8.297222  
2000-12-03 18:00:00 8.110486  
2000-12-04 00:00:00 8.066154

我尝试使用arima()模型实现预测:

requires(forecast)
fit <- Arima(stock$value,c(3,1,2))
fcast <- forecast(fit, h = 5)

之后我想从预测过程中获取情节。但是我试着让x轴有日子。到现在为止我有这个:

x = as.POSIXct( stock$day , format = "%Y-%m-%d %H:%M:%S" )

plot(fcast, xaxt="n")
a = seq(x[1], by="min", length=nrow(stock))
axis(1, at = a, labels = format(a, "%Y-%m-%d %H:%M:%S"), cex.axis=0.6)

1 个答案:

答案 0 :(得分:2)

因为你操纵时间序列对象,所以最好使用像zooxts这样的ts包。似乎forecast包被设计用于处理这些对象。

## read the zoo object
## I add a virtual colname aaa here 
## for some reason index=0:1 don't work
library(zoo)
stock <- read.zoo(text='aaa day value
2000-12-01 00:00:00 11.809242 
2000-12-01 06:00:00 10.919792 
2000-12-01 12:00:00 13.265208 
2000-12-01 18:00:00 13.005139 
2000-12-02 00:00:00 10.592222  
2000-12-02 06:00:00 8.873160 
2000-12-02 12:00:00 12.292847 
2000-12-02 18:00:00 12.609722 
2000-12-03 00:00:00 11.378299 
2000-12-03 06:00:00 10.510972  
2000-12-03 12:00:00 8.297222  
2000-12-03 18:00:00 8.110486  
2000-12-04 00:00:00 8.066154',header=TRUE,
                tz='',
                index=1:2)

##  arima works well with zoo objects
fit <- Arima(stock,c(3,1,2))
fcast <- forecast(fit, h = 20)
plot(fcast, xaxt="n")

要绘制日期轴,您应使用axis.POSIXctaxis.Date。日期对象有等效的axis。但您应该首先创建日期索引。在这里,我汇总了forecast函数生成的原始日期和预测日期。

  a <- c(as.POSIXct(index(stock)),
         as.POSIXct(index(fcast$mean),origin='1970-01-01 00:00.00 UTC'))

然后我用这样的东西绘制我的轴:

## Note the use of las to rotate the axis 
## you can play with format here
axis.POSIXct(1,at=a,format="%a %H",las=2,cex=0.5)

enter image description here