如何用真实的观察来绘制拟合值和预测值

时间:2016-07-09 18:58:00

标签: r plot ggplot2 time-series forecasting

我有训练数据和测试数据,我在tbats包中使用forecast拟合模型。

demand.train<-demand[1:94920,]
demand.train.ts<-msts(demand.train$Demand,seasonal.period=c(48,7*48,91.25*48,365*48),start=2011)
demand.train.model<-tbats(demand.train.ts)
fc1.week<-forecast(demand.train.model,h=48*7)
plot(fc1.week)

我想知道:

  1. 如何在同一图中绘制拟合值和真实观测值?
  2. 如何绘制预测值及其置信区间? (plot可以做到这一点,但我的时间序列太大,预测值在情节的最后,因此难以观察。我想要一个只有预测值和CI,而不包括所有以前的时间序列)
  3. 如何将测试数据添加到第二个图中。
  4. 谢谢!

2 个答案:

答案 0 :(得分:2)

您可能需要考虑以下两种方式:

首先让我们获取一些免费的数据

library(ggplot2)
my_data <- mtcars

在绘图函数中显示预测,作为置信区间

的线
plot_internal <- ggplot(my_data)+
  aes(x = wt, y = mpg)+
  # raw data
  geom_point()+
  # LM 
  geom_smooth(method = "lm")
plot_internal

enter image description here

我怀疑你真的想知道如何根据显式模型显示预测。以下是如何做到这一点:

my_model <- lm(mpg ~ wt, data=my_data)

# add the fitted values right into the data frame
my_data$fitted <- fitted(my_model)

现在将实际值和拟合值绘制为单独的图层。

plot_external <- ggplot(my_data)+
  aes(x = wt)+
  # raw data
  geom_point(aes(y = mpg))+
  # fitted values
  geom_point(aes(y=fitted), color = "purple")
plot_external

enter image description here

特殊酱:绘制连接实际值和拟合值的箭头

plot_with_residual_arrows <- ggplot(my_data)+
  aes(x = wt)+
  # raw data
  geom_point(aes(y = mpg))+
  # fitted values
  geom_point(aes(y=fitted), color = "purple")+
  # plot arrows from predicted to real values
  geom_segment(aes(xend = wt, y = fitted, yend = mpg),
               arrow = arrow(length = unit(0.4, "line")), 
               color="red")
plot_with_residual_arrows

enter image description here

旁注:在这些情况下,有时候指定真实值和拟合值的图例很好。关于SO的各种其他问题可以帮助您解决这个问题 - 它只是简化数据融化或设置明确的传说。

答案 1 :(得分:0)

目前我还没有时间详细说明。

看一下RPub中的这篇文章,你会发现你需要的东西:

https://rpubs.com/RatherBit/102453