2

I want to make a plot with days in x axis from the forecast process. I made an example using the guides from here: https://stackoverflow.com/a/10347205/2366057

The example from the link:

 Lines <- "Date        Used
 2011-11-1/00:00:00   587
 2011-11-2/01:00:00   578
 2011-11-3/02:00:00   600
 2011-11-4/03:00:00   599
 2011-11-5/04:00:00   678
 2011-11-6/05:00:00   555
 2011-11-7/06:00:00   650"

 dm <- read.table(text = Lines, header = TRUE)
 x = dm
require(lubridate)
library(forecast)
 y = ts(x$Used, start=c(2011, yday("2011-11-01")), frequency=365)
 fcast = forecast(ets(y), 10)
 plot(fcast, xaxt="n")
  a3 = strptime(x$Date, "%Y-%m-%d/%H:%M:%S")
 axis(1, at = decimal_date(a3), labels = format(a3, "%Y-%b-%d %H:%M:%S"), cex.axis=0.3, las=2)

My data:

"day","price"
"2010-02-12 00:00:00",12
"2010-02-12 01:00:00",14
"2010-02-12 02:00:00",15
"2010-02-12 03:00:00",14
"2010-02-12 04:00:00",13
"2010-02-12 05:00:00",16

I have my data into a csv file and as the above:

 df = read.csv(filepath, header=TRUE, sep=",")

 require(lubridate)
 library(forecast)
 y = ts(df$price)
 fcast = forecast(ets(y), 10)

 plot(fcast, xaxt="n")
 a3 = strptime(df$day, "%Y-%m-%d %H:%M:%S")
 axis(1, at = decimal_date(a3), labels = format(a3, "%Y-%b-%d %H:%M:%S"), cex.axis=0.6, las=2)

In the second snippet in the x-axis the days doesn't appear. What is it wrong?

Thank you in advance.

4

1 回答 1

2

在您的第一个片段中,请注意这一行:

y = ts(x$Used, start=c(2011, yday("2011-11-01")), frequency=365)

使用实际观察的日期创建时间序列。这些日期的十进制表示形式存储y并用于绘制时间序列,当您稍后绘制轴并传入时decimal_date(a3),事情就会匹配。

unclass(y)
# [1] 587 578 600 599 678 555 650
# attr(,"tsp")
# [1] 2011.833 2011.849  365.000
decimal_date(a3)
# [1] 2011.833 2011.836 2011.838 2011.841 2011.844 2011.847 2011.850

看看数字是如何相似的?

但是您没有在第二个片段中包含这些日期:

y = ts(df$price)

因此,观察结果仅绘制在 1、2、3、4、5 和 6 处。但是您再次将decimal_date(a3)--values 传递到屏幕外。

unclass(y)
# [1] 12 14 15 14 13 16
# attr(,"tsp")
# [1] 1 6 1
decimal_date(a3)
# [1] 2010.115 2010.115 2010.115 2010.115 2010.116 2010.116

但请注意其他事情:其中许多decimal_date值是相同的。那是因为您在第二个片段中的观察结果是按小时而不是按天计算的。这不是你想要的功能。

一种解决方法是在创建轴时坚持使用 1-6 编号:

axis(1, at = seq_along(a3), labels = format(a3, "%Y-%b-%d %H:%M:%S"), cex.axis=0.6, las=2)

另一种方法是在创建时间序列和绘制标签时将日期转换为秒:

df$day <- as.POSIXlt(df$day)

y = zoo(df$price, df$day)

axis(1, at = as.numeric(df$day), labels = format(a3, "%Y-%b-%d %H:%M:%S"), cex.axis=0.6, las=2)

(此时,您可能不应该为变量命名day。)

于 2013-09-07T14:15:42.147 回答