gpt4 book ai didi

r - x 轴绘图包含日期

转载 作者:行者123 更新时间:2023-12-04 11:05:54 26 4
gpt4 key购买 nike

我用这个数据加载一个数据框(命名为股票):

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)

最佳答案

因为,你操纵时间序列对象,所以最好使用像 zooxts 这样的 ts-packages,看来 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

关于r - x 轴绘图包含日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17121173/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com