【问题标题】:Plot forecast and actual values绘制预测值和实际值
【发布时间】:2019-12-02 09:59:53
【问题描述】:

我都是。我需要统计专家的帮助。我对as 中的几个值做了一个简单的有马预测。但我在train_as 中取了一部分值。

现在有一种方法可以在此处绘制实际值和预测值。就像 2019 年的实际值为 4、8、12、16,预测为 9、10、11、12。我们可以绘制这个吗?

as <- data.frame(a=c(1,2,3,4,2,4,6,8,4,8,12,16))
train_as <- as[c(1:8),]
a1 <- ts(train_as,start = c(2017,1),end = c(2017,8),frequency = 4)
fit_arima <-auto.arima(a1, trace= TRUE, ic ="aic")
print(summary(fit_arima))
checkresiduals(fit_arima)
fcst <- forecast(fit_arima,h=4)
autoplot(fcst,include = 8)

【问题讨论】:

标签: r time-series forecasting


【解决方案1】:

使用带有autolayer() 函数的预测包很容易做到这一点。

library(forecast)
library(ggplot2)

as <- data.frame(a = c(1, 2, 3, 4, 2, 4, 6, 8, 4, 8, 12, 16))

# Convert to a time series
y <- ts(as$a, start = 2017, frequency = 4)

# Split in two
a1 <- subset(y, end = 8)
a2 <- subset(y, start = 9)

# Fit model
fit_arima <- auto.arima(a1, ic = "aic")

# Compute forecasts
fcst <- forecast(fit_arima, h = 4)

# Plot forecasts and test set
autoplot(fcst) + autolayer(a2)

reprex package (v0.3.0) 于 2019 年 12 月 2 日创建

【讨论】:

    【解决方案2】:

    你可以尝试这样的事情,首先你创建你的测试数据集:

    test_as <- as[c(9:12),]
    

    现在要绘制data.frame,您可以看到real 数据、time 以及应该具有相同时间长度和真实数据的预测值(及其 IC),所以我粘贴了一个NAs 向量,其长度等于真实数据与预测数据和预测数据之间的差异(IC 相同)。请注意,时间是使用zoo 包按季度生成的:

    library(zoo)
    df <-
    data.frame(real = as$a,
               pred = c(rep(NA,length(as$a)-length(data.frame(fcst)[,1])),data.frame(fcst)[,1]),
               time =  zoo::as.yearqtr(seq(as.Date("2017/1/1"), as.Date("2019/12/1"), by = "quarter"), format = "%Y-%m-%d"),
               Lo80 =c(rep(NA,length(as$a)-length(data.frame(fcst)[,2])),data.frame(fcst)[,2]),
               Hi80 =c(rep(NA,length(as$a)-length(data.frame(fcst)[,3])),data.frame(fcst)[,3]),
               Lo95 =c(rep(NA,length(as$a)-length(data.frame(fcst)[,4])),data.frame(fcst)[,4]),
               Hi95 =c(rep(NA,length(as$a)-length(data.frame(fcst)[,5])),data.frame(fcst)[,5])) 
    

    现在你可以绘制它了:

    library(ggplot2)
    ggplot(df, aes(time, pred, group = 1)) +
      geom_line() +
      geom_line(aes(time, real, group = 1), color = "red")+
      geom_ribbon(aes(time, ymin = Lo95, ymax = Hi95), fill = "red", alpha = 0.25) +
      geom_ribbon(aes(time, ymin = Lo80, ymax = Hi80), fill = "red", alpha = 0.25) +
      theme_light()
    

    【讨论】:

      猜你喜欢
      • 2014-12-21
      • 2021-11-11
      • 1970-01-01
      • 2021-04-08
      • 2020-12-04
      • 1970-01-01
      • 1970-01-01
      • 2019-04-10
      • 2020-06-26
      相关资源
      最近更新 更多