问题
Good day
I read on one of the posts here that "the function forecast::plot.forecast is not designed to be used with axis.Date or axis.POSIXct (which are not used in the package forecast)." This can be seen here:custom axis labels plotting a forecast in R
Nevertheless, they managed to use the forecast package and some code to get the correct axis labels. However, this example is for quarterly data. Also, this example here using 'as.POSIXlt' is for weekly data: Forecasting time series data
I've tried playing with the code but I can't get it to work for monthly data. So my axis labels are still wrong. I'm stumped. Please would you help advise how I get the axis labels to reflect correctly using the forecast package?
Example
library(forecast)
headcount<-c(2475,2468,2452,2464,2500,2548,2536,2565,2590,2608,2625,2663)
date<-c("2013/01/31","2013/02/28","2013/03/31","2013/04/30","2013/05/31","2013/06/30",
"2013/07/31","2013/08/31","2013/09/30","2013/10/31","2013/11/30","2013/12/31")
x<-data.frame(headcount,date)
t<-ts(x$headcount,start=c(2013,1),end=c(2013,12),frequency=12)
fit<-forecast(t,h=12)
plot(forecast(fit))
By doing this, the axis labels come out as 2013.0, 2013.5, 2014.5
I know this is only a year's worth of data. I'm just interested in how to fix the axis labels for monthly data,
Kind regards D
回答1:
Here's a possible solution using the links provided
plot(forecast(fit), axes = FALSE)
a <- seq(as.Date(date[1]) + 1, by = "months", length = length(date) + 11)
axis(1, at = as.numeric(a)/365.3 + 1970, labels = format(a, format = "%m/%Y"), cex.axis = 0.9)
axis(2, cex.axis = 0.9)
来源:https://stackoverflow.com/questions/26625549/r-forecasting-with-as-posixlt-ct