How to show to date instead of periods at x-axis in time series forecast plot?

3.6k Views Asked by At

I have a simple time series dataset: df1, in format like:

    Item | Date     | Var
      1  | 20000101 | 12
      2  | 20000102 | 13
      3  | 20000103 | 16
      4  | 20000104 | 18
      5  | 20000105 | 29
      6  | 20000106 | 36
      ...
      ...
      ...
      ...
      365| 20001231 | 78

My code is:

    varts <- ts(df1$var, frequency=7)
    comp <- decompose(varts)
    plot(comp)
    fcmodel <- HoltWinters(varts)
    plot(forecast(fcmodel, h=30, level=c(80,95)))

I got a simple forecast plot but the x-axis ranges from 0 to 50 instead of the date.
I would like to present the plot with real date at x-axis, which is meaningful to explain my data.
But I am lost in tons of explanation on the web, failed with every method I found.
I really appreciate if anyone could help with this question.

1

There are 1 best solutions below

3
On BEST ANSWER
library(forecast)
library(lubridate)

# generate dummy data
df1 <- data.frame(seq(1, 365, 1), seq(as.Date('2000-01-01'), as.Date('2000-12-30'), 1), round(100*runif(365), 0))
names(df1) <- c('item','date','var')

varts <- ts(df1$var, frequency=7)
comp <- decompose(varts)
plot(comp)
fcmodel <- HoltWinters(varts)

plot(forecast(fcmodel, h=30, level=c(80,95)), xaxt='n')
axis(1, at=seq(0, 80,10) , las=2, labels=seq(as.Date('2000-01-01'), as.Date('2000-12-31')+weeks(30), length.out=9) )

The last two lines essentially copy the approach from here Replace X-axis with own values.

You can edit the labels and their locations by editing the 'at=' and 'lables=' -parameters.

Here is what the output looks like