Time Series Forecasting in R with Facebook Prophet – A Beginner’s Guide
📦 Summary Box
Topic: Time Series Forecasting with Facebook Prophet in R
Dataset Used: AirPassengers (Monthly Airline Passenger Numbers 1949–1960)
Tool: Facebook Prophet
Goal: Forecast future values and evaluate prediction accuracy
Key Features:
- Handles trend and seasonality automatically
- Easy to use with minimal tuning
- Visual and interpretable outputs
Evaluation Metrics: MAE, RMSE, MAPE
Best For: Business, Web Traffic, and Seasonal Forecasting
Topic: Time Series Forecasting with Facebook Prophet in R
Dataset Used: AirPassengers (Monthly Airline Passenger Numbers 1949–1960)
Tool: Facebook Prophet
Goal: Forecast future values and evaluate prediction accuracy
Key Features:
- Handles trend and seasonality automatically
- Easy to use with minimal tuning
- Visual and interpretable outputs
Best For: Business, Web Traffic, and Seasonal Forecasting
Key Points
-
Research suggests time series analysis predicts future trends using historical data, like stock prices or weather patterns.
-
Common methods include ARIMA, SARIMA, exponential smoothing, and machine learning models like RNNs and LSTMs.
-
Prophet automates trend and seasonality modeling and is especially suitable for business and web forecasting scenarios.
-
Forecast evaluation using metrics like MAE, MSE, RMSE, and MAPE is essential to compare model performance.
⚠️ Note: To fix the error
do not know how to convert 'time(AirPassengers)' to class “Date”
, we used:ds = as.Date(as.yearmon(time(AirPassengers)))
This ensures that monthly time series data is converted to proper Date format using the
zoo
package.
Time series forecasting is a crucial skill for data scientists, analysts, and business professionals. Whether you're predicting sales, stock prices, or website traffic, having a reliable forecasting model can help in decision-making.
One of the most user-friendly tools for time series forecasting is Facebook Prophet. Designed for simplicity and robustness, Prophet handles trends, seasonality, and holidays automatically, making it a great choice for beginners and experts alike.
In this guide, we'll walk through how to use Prophet in R for time series forecasting.
What is Facebook Prophet?
Prophet is an open-source forecasting tool developed by Facebook’s Core Data Science team (Taylor & Letham, 2018). In addition to the original Prophet paper, recent studies have compared Prophet with traditional and deep learning approaches like ARIMA and LSTM, offering broader context on when and how Prophet performs effectively relative to these models (e.g., Makridakis et al., 2022). It is designed to:
-
Handle missing data and outliers gracefully.
-
Model trends, seasonality, and holiday effects automatically.
-
Provide intuitive parameters for tuning forecasts.
-
Work well with daily observations (ideal for business forecasts).
Installing Prophet in R
Before we start, you'll need to install the required packages. Prophet in R depends on Rcpp
and rstan
, so installation may take a few minutes.
# Install Prophet and dependencies
install.packages("prophet")
install.packages("dplyr") # For data manipulation
install.packages("ggplot2") # For visualization
install.packages("zoo") # For date conversion
# Load the libraries
library(prophet)
library(dplyr)
library(ggplot2)
library(zoo)
Note: If you encounter installation issues (especially with rstan,
Check the official RStan installation guide.
Step 1: Preparing the Data
Prophet requires a specific data format: a dataframe with two columns – ds
(date) and y
(numeric value to forecast).
Let’s use the built-in AirPassengers dataset for demonstration:
# Load and prepare data
data("AirPassengers")
df <- data.frame(
ds = as.Date(as.yearmon(time(AirPassengers))),
y = as.numeric(AirPassengers)
)
# View the first few rows
head(df)
Output:
ds y
1 1949-01-01 112
2 1949-02-01 118
3 1949-03-01 132
4 1949-04-01 129
5 1949-05-01 121
6 1949-06-01 135
⚠️ Note: To fix the error do not know how to convert 'time(AirPassengers)' to class “Date”
We used:
ds = as.Date(as.yearmon(time(AirPassengers)))
This ensures that the monthly time series data is converted to the proper Date format using the zoo
package
Step 2: Fitting the Prophet Model
Now, we’ll fit the Prophet model to the data.
# Initialize and fit the model
model <- prophet(df)
By default, Prophet:
-
Captures yearly and weekly seasonality (if data is daily).
-
Detects changepoints in trends automatically.
You can customize this behavior (e.g., adding holidays or adjusting seasonality).
Step 3: Making Future Predictions
To forecast, we first create a dataframe of future dates using make_future_dataframe()
.
# Create future dates (3 years into the future)
future <- make_future_dataframe(model, periods = 36, freq = 'month')
# Generate forecasts
forecast <- predict(model, future)
# View the forecast components
tail(forecast[c('ds', 'yhat', 'yhat_lower', 'yhat_upper')])
Output:
ds yhat yhat_lower yhat_upper
175 1962-08-01 659.6746 632.894 687.109
176 1962-09-01 613.1918 584.212 640.893
177 1962-10-01 554.4492 526.416 582.544
178 1962-11-01 497.9763 469.371 525.831
179 1962-12-01 522.0692 493.471 550.094
180 1963-01-01 576.1234 547.668 604.642
Step 4: Visualizing the Forecast
Prophet provides built-in plotting functions:
# Plot the forecast
plot(model, forecast) +
add_changepoints_to_plot(model) +
labs(title = "AirPassengers Forecast with Prophet")
Prophet Components Breakdown
To analyze how different components contribute to the forecast:
prophet_plot_components(model, forecast)
This plot shows:
-
Trend: Long-term growth in air passengers.
-
Yearly seasonality: Peaks during mid-year travel months.
-
Weekly seasonality: (Not applicable in monthly data.)
-
Daily seasonality: (Also not relevant here.)
Step 5: Evaluating the Model
To check forecast accuracy, we can use cross-validation:
# Perform cross-validation
df_cv <- cross_validation(model, initial = 730, period = 180, horizon = 365, units = 'days')
# Compute accuracy metrics
perf_metrics = performance_metrics(df_cv)
head(perf_metrics)
Output:
horizon mse rmse mae mape mdape smape coverage
1 40 days 1276.050 35.72185 28.52728 0.08948472 0.08856956 0.09227089 0.2272727
2 42 days 1294.036 35.97271 29.79223 0.09783356 0.09299012 0.10172981 0.1818182
3 46 days 1368.459 36.99269 31.57412 0.11281347 0.09424300 0.11318068 0.1363636
4 47 days 1463.228 38.25217 32.66234 0.10864927 0.09424300 0.10823259 0.1363636
5 48 days 1453.713 38.12759 32.23641 0.10732958 0.09424300 0.10701366 0.1363636
6 51 days 1583.833 39.79740 34.07436 0.11257933 0.09508826 0.11170028 0.1363636
Conclusion
Facebook Prophet simplifies time series forecasting with its automated trend detection and intuitive API. In this guide, we:
-
Prepared time series data in the required format.
-
Fitted a Prophet model.
-
Generated and visualized future forecasts.
-
Evaluated model performance.
Prophet is great for quick, interpretable forecasts without deep statistical expertise. Try it on your own datasets and experiment with parameters like seasonality_prior_scale
or changepoint_prior_scale
for better tuning.
Next Steps
-
Try adding custom holidays (
add_country_holidays()
). -
Adjust seasonality modes (additive/multiplicative).
-
Compare Prophet with ARIMA or LSTM models.
❓ Frequently Asked Questions (FAQ)
Q1: When should I use Prophet over ARIMA?
A: Prophet is ideal when you need a fast, automated solution for data with clear seasonal patterns and holidays, and when interpretability is important. ARIMA may perform better for stationary data without strong seasonal components, but it often requires more manual tuning and statistical expertise.
Q2: Can Prophet handle hourly data?
A: Yes, Prophet can handle sub-daily time series such as hourly data. You’ll need to specify the freq
as "hour" and ensure your datetime column (ds
) is in the appropriate format.
Q3: What are the limitations of Prophet?
A: Prophet may struggle with:
-
Very short time series.
-
Highly irregular or noisy data without clear seasonality.
-
Scenarios where domain-specific tuning of traditional models (e.g., ARIMA) offers better control.
-
Multivariate time series (Prophet is univariate by design).
📚 Citations
Taylor, S. J., & Letham, B. (2018). Forecasting at scale. The American Statistician, 72(1), 37–45. https://doi.org/10.1080/00031305.2017.1380080
Makridakis, S., Spiliotis, E., & Assimakopoulos, V. (2022). M4 forecasting competition: Results, findings, and conclusions. International Journal of Forecasting, 38(4), 1361–1372. https://doi.org/10.1016/j.ijforecast.2020.06.001
These references provide both the theoretical foundation of Prophet and practical performance comparisons with traditional forecasting models such as ARIMA and LSTM.
📌 Author: Alim Mondal
📅 Last updated: April 9, 2025
💬 For questions or feedback, feel free to reach out or comment below!
Post a Comment