Reputation: 2605
I am trying to compare the forecasts from R forecast package with the forecast from R Facebook Prophet package.
the forecast package comes with a convenient autoplot function, which seems to work only with objects from the class forecast.
When I try to plot the forecast generated by Prophet, I get the following error:
> autoplot(forecast$yhat)
Error: Objects of type numeric not supported by autoplot.
How to a convert a data frame or a vector into a forecast object that can then be displayed using the autoplot function?
Upvotes: 0
Views: 1244
Reputation: 2289
The first thing is that as.forecast does not exist, however I found an alternative that can be useful
library(prophet)
library(dplyr)
df <- read.csv('https://raw.githubusercontent.com/facebook/prophet/master/examples/example_wp_peyton_manning.csv') %>% mutate(y = log(y))
this is the prophet object
m <- prophet(df)
Disabling daily seasonality. Run prophet with daily.seasonality=TRUE to override this.
Initial log joint probability = -19.4685
Optimization terminated normally:
Convergence detected: relative gradient magnitude is below tolerance
future <- make_future_dataframe(m, periods = 365)
library(zoo)
serie <- zoo(df$y, order.by = as.Date(df$ds))
autoplot(serie)
forecast <- predict(m, future)
|======================================================================================|100% ~0 s remaining > tail(forecast[c('ds', 'yhat', 'yhat_lower', 'yhat_upper')])
ds yhat yhat_lower yhat_upper
3265 2017-01-14 7.823991 7.092573 8.580624
3266 2017-01-15 8.205770 7.483129 8.946540
3267 2017-01-16 8.530798 7.791047 9.278295
3268 2017-01-17 8.318204 7.615776 9.016683
3269 2017-01-18 8.150827 7.462445 8.883549
3270 2017-01-19 8.162741 7.494982 8.846622
Here is the error that you mention
autoplot(forecast$yhat)
Error: Objects of type numeric not supported by autoplot.
using the forecast library and the function the autoplot
of the ggfortify package
plot(m, forecast)
library(forecast)
mod <- auto.arima(serie)
autoplot(forecast(mod, h = 365))
df2 <- data.frame(ds = c(as.Date(df$ds),as.Date(forecast$ds)), y = c(df$y,forecast$yhat))
par(mar=c(3,3,2,2),mgp=c(1.6,.6,0))
plot(df2$ds,df2$y, type = "n", ylab = "y", xlab = "ds", las = 1, cex.axis = 0.7)
rect(par("usr")[1], par("usr")[3],par("usr")[2],par("usr")[4],col=gray(.9,.9),
border='white');grid(lty=1, col='white')
lines(as.Date(df$ds),df$y)
lines(as.Date(tail(forecast$ds, n = 365)),tail(forecast$yhat, n = 365), col = "blue4")
lines(as.Date(tail(forecast$ds, n = 365)),tail(forecast$yhat_lower, n = 365), col = "grey40")
lines(as.Date(tail(forecast$ds, n = 365)),tail(forecast$yhat_upper, n = 365), col = "grey40")
At first glance, the difference is minimal and goes unnoticed. Although you could use ggplot2, it is the same as autoplot.
Upvotes: 1