向预测图添加月份

时间:2019-08-30 23:40:12

标签: r ggplot2 forecasting

我使用2017年1月至2019年7月的月度数据生成了一年预测,并使用了创新的状态空间模型进行指数平滑。

library("forecast") 
library("ggplot2")
library("scales")

myData<-c(11878838,11025085,13346905,11657777,12670973,12321707,10668589,13296366,10976129,13383487,11157827,9064816,
          10712529,11058177,11220417,12010494,11824792,10623115,10171066,13388616,11249052,14134987,10795036,9001540,
          10561734,10658972,11689656,10351909,11062358,9858083,9779142)

ts_myData<-ts(myData, frequency=12, start=c(2017,1), end=c(2019,7))

model<-ets(ts_myData, model="MNM")

fcast_units<-forecast(model, h=12, PI=TRUE)  

autoplot(fcast_units)+
  xlab("Year")+
  ylab("Number of units")+
  ggtitle("My forecast")+
  scale_y_continuous(label=comma) # this line is to avoid scientific notation and use the format you see on the y-label

问题是我想更改绘图的x轴,但似乎无法弄清楚该怎么做。我想看到从2017年1月到2020年7月的所有月份。现在的情节看起来像这样。

plot of past observations and forecast

如果查看当前图,则可以推断出白色竖线代表一年的开始和结束以及六月的月份,但我希望每年都有12条。我尝试使用scale_x_datescale_x_datetime,但是它们不起作用(也许我没有正确指定参数?)。也许问题是fcast属于forecast类?我不确定。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

这种代码的工作方式。

autoplot(fcast_units)+
  xlab("Year")+
  ylab("Number of units")+
  ggtitle("My forecast")+
  scale_y_continuous(label=comma)+
  scale_x_continuous(breaks = seq(2017 , 2020, 1/6))
相关问题