Search code examples
rdatetimeforecast

How to change the x axis in a ts object to %Y-%m-%d format from as.numeric


I am attempting to implement a forecast based on a time series object. However, when I'm getting graphs out of the code the x-axis is as.numeric version of the date:

enter image description here

Here's a snapshot of the subset of data used: enter image description here

Code used:

ts<-ts(temp$total_cases, frequency = 1, start = min(as.Date(temp$date,"%Y-%m-%d")), end = max(as.Date(temp$date,"%Y-%m-%d")))

# time series labeled object for country's dates and
assign(paste0('ts_',country),ts)

fit <- ets(ts_Afghanistan)

plot(forecast(fit))

When I enter the following the transition to date of the type of output on the x axis is clear:

> as.Date(18300)
[1] "2020-02-08"

Just not sure how to get this reflected in the x-axis label. I tried playing with zoo and other functions without success. Would appreciate help on this.


Solution

  • One way is to override the x-axis. In most base plot methods, xaxt="n" suppresses the default axis. After that, you axis to define a plot. (axTicks provides a good set of default tick locations.)

    vec <- 18300 + 0:10
    plot(vec, vec, xaxt = "n")
    axTicks(1)
    # [1] 18300 18302 18304 18306 18308 18310
    axis(1, at = axTicks(1), labels = as.character(as.Date(axTicks(1))))
    

    basic plot