rforecasting

How do I change the x-axis from showing decimal form for Year/Month with a graphed time series in R?


I'm very new to R but with some Googling and ChatGPT I've managed to muddle through graphing a forecast from a time series.

Below is not my real data but I'm trying to provide a simple reproducible set of steps and data.

My issue is the x-axis is in the form of year month ("2022 Nov", "2022 Dec", "2023 Jan", etc) but it is being labeled on the graph as a decimal number. I have not been successful in finding how to make this display in the form of year month on the x-axis.

# Create a tsibble
myTsibble <- tsibble(
  YearMonth = seq(yearmonth("2022-11"), length.out = 12, by = 1),
  Value = c(3, 2, 1, 4, 4, 3, 6, 5, 7, 10, 7, 8),
  index = YearMonth
)

# Create a time series
myTimeSeries <- ts(
  myTsibble$Value, 
  frequency = 12, 
  start = c(year(min(myTsibble$YearMonth)), month(min(myTsibble$YearMonth)))
)

# Graph the simple exponential smoothing forecast from the time series
mySes <- ses(myTimeSeries)
plot(mySes, main = "Item ABC", ylab = "Units Sold", xlab = "Year Month")
axis.Date(1, at = time(myTimeSeries), format = "%b %Y")

The last line of code produces an error "Error in as.Date.default(if (has.at) at else x) : do not know how to convert 'if (has.at) at else x' to class "Date""

I cannot find any information about this error message and I'm not sure what exactly is happening here. I don't think any of the objects are a "Date" class but I'm not sure.

In the attached image you can see that the x-axis is displaying "2023.0", "2023.5", "2024.0", and "2024.5". I would like these to be displayed as their Year Month pair (2023 Jan, 2023 Feb, etc.).

Any help is appreciated!

Image of Graph


Solution

  • The key is to work out the sequence of date breaks you want.

    dates <- seq(as.Date("2022-11-01"), by = "month", length = 22)
    

    Now plot without an x axis:

    plot(mySes, main = "Item ABC", ylab = "Units Sold", 
         xlab = "Year Month", xaxt = "n")
    

    And add your breaks in decimal format to at and formatted as month-year to labels

    axis(1, at = lubridate::decimal_date(dates), labels = format(dates, "%b %Y"))
    

    enter image description here