moka
moka

Reputation: 35

Manipulating x-axis for forecast/timeseries objects

Good day,

I am trying to cut off/zoom in the right side of a forecast generated in R. Timeseries/ARIMA code is shown below. I've tried multiple ways using subset, xlimit but I could not get anyway. I've tried coord_cartersian but I am not certain that would work for forecast data set (tried to research forecast/ggplot packages documentation with no clear answer).

Below is my code

#time series from January 1st       2012 until 10th of august 2016
dd = ts(data = dailydemand, frequency = 365) 
dd.arima = auto.arima(dd) # Auto arima
dd.f = forecast.Arima(dd.arima, h = 7) # forecast 7 days
# getting the quantity needed for next day
n2.cnt = as.data.frame(dd.f) 
n2.cnt = as.numeric(round(dd.f [1,1]) ) 
autoplot(dd.f) + 
  ggtitle("Daily demand forecast") + 
  ylab("Count of cars") +
  geom_hline(dd.f, yintercept = n2.cnt)  

coord_cartesian didnt work, I've also tried zoom package to zoom in last 3 days

Upvotes: 3

Views: 1460

Answers (1)

Weihuang Wong
Weihuang Wong

Reputation: 13118

coord_cartesian seems to work for me. You did not provide a minimal reproducible example (please do so next time), so here I've used the AirPassengers dataset as an example.

library(forecast)
library(ggplot2)
library(gridExtra)

dd <- AirPassengers
dd.arima <- auto.arima(dd) # Auto arima
dd.f <- forecast.Arima(dd.arima, h = 12) # forecast 12 months

Inspect attr(dd.f$x, "tsp"). The x-axis appears to be in actual years, so we express the limits in coord_cartesian accordingly:

attr(dd.f$x, "tsp")
# [1] 1949.000 1960.917   12.000   
g1 <- autoplot(dd.f) + 
  ggtitle("Air passengers forecast") + 
  ylab("y") 
g2 <- autoplot(dd.f) + 
  ggtitle("Air passengers forecast") + 
  ylab("y") +
  coord_cartesian(xlim = c(1960, 1962.1))
grid.arrange(g1, g2, ncol=2)

enter image description here

Upvotes: 4

Related Questions