Custom Axis Labels Displaying Forecast in R

I am trying to get some sensible shortcuts in the forecast.

Here's my code:

library("forecast")

t <- ts(
  c(
    4410.0, 6435.0, 
    4939.0, 6487.0, 25521.0, 18764.0, 
    12223.0, 18590.0, 36898.0, 28826.0, 
    20329.0
    )  
  , frequency = 4
  , start=c(2011, 7, 1)
)

cast <- meanf(t,h=4)

par(mfrow=c(1,1),xaxt="n")
plot(cast)

ticks <- seq(as.POSIXct("2011-07-01"), by = "3 month", length.out=length(cast) + 4) 
axis.Date(1, at = ticks, labels = ticks, format="%Y-%m")

      

No errors or warnings ... but no axis is added to the plot :(

If I use xaxt="s"

then I get the axis labels, but they are not the same as 2014.0 (i.e. not formatted as dates at all). Ideally, I would really like something more readable like "Q3 2014", but I would settle for 2014-07 (first month of the quarter).

Any idea what I am doing wrong? All the stuff I've found on the internet suggests disabling the default axis and then using the axis or .Date axis functions to add the UI ... but I can't get any type of axis using any of these methods :(

+2


source to share


1 answer


I would not say there is a bug and the function is forecast::plot.forecast

not intended to be used with axis.Date

or axis.POSIXct

(which are not used in the package forecast

).

Before calling functions axis.Date

and axis.POSIXct

time points must be explicitly passed in plot

as a sequence of objects Date

or POSIXct

. If we plot the time series as plot(t)

then the x-axis will not be correctly identified as being used by the above functions.



See the code below and how a variable is created time

and passed to plot

. plot(time, x)

used instead of plot(x)

. This way the function axis

will be able to display time axis labels. (In this example, the confidence intervals will not look as good as they appear forecast::plot.forecast

.)

library("forecast")
require(zoo)

t <- ts(
  c(
    4410.0, 6435.0, 
    4939.0, 6487.0, 25521.0, 18764.0, 
    12223.0, 18590.0, 36898.0, 28826.0, 
    20329.0
    )  
  , frequency = 4
  , start=c(2011, 7, 1)
)
cast <- meanf(t, h=4)

x <- ts(c(t, cast$mean), start = c(start(t), 1), frequency = frequency(t))
time <- as.yearqtr(seq(start(x)[1], end(x)[1] + 1, 1/frequency(x)))
time <- time[seq_along(x)]
time <- as.POSIXct(time)
plot(time, x, type = "n", xaxt = "n", ylim = range(c(cast$lower, cast$upper)))
lines(time[seq_along(t)], t)
lines(time[-seq_along(t)], cast$mean, col = "blue")
lines(time[-seq_along(t)], cast$upper[,2], col = "red")
lines(time[-seq_along(t)], cast$lower[,2], col = "red")
ticks <- seq(as.POSIXct("2011-07-01"), by = "3 month", length.out=length(cast) + 4) 
axis(side = 1, at = ticks, labels = ticks)

      

+1


source







All Articles