Introduction
Time series analysis is essential for forecasting and understanding trends in sequential data. In this tutorial, we provide side-by-side examples using Facebook Prophet—a popular tool for time series forecasting—in both Python and R. You’ll learn how to prepare your data, fit a model, and visualize future trends, allowing you to compare workflows and choose the best approach for your projects.
Using Facebook Prophet for Time Series Forecasting
Below, you’ll find a panel-tabset that demonstrates how to build and visualize a forecast using Prophet in both Python and R.
STEP 1. Load Required Packages:
#| label: python-required-packages
import pandas as pd
import numpy as np
from prophet import Prophet
import matplotlib.pyplot as plt
STEP 2. Load and Transform Data:
#| label: python-load-data
# Load the AirPassengers dataset
= pd.read_csv("https://raw.githubusercontent.com/kassambara/datarium/refs/heads/main/data-raw/AirPassengersDf.csv")
air_passengers
# Convert the time values to a proper Date format
= pd.DataFrame({
df 'ds': pd.to_datetime(air_passengers['Month']),
'y': air_passengers['Passengers']
}) df.head()
ds y
0 1949-01-01 112
1 1949-02-01 118
2 1949-03-01 132
3 1949-04-01 129
4 1949-05-01 121
The AirPassengers
dataset contains monthly data for passenger numbers.
STEP 3. Fit the Prophet Model:
#| label: python-prophet-fit
# Fit the Prophet model
= Prophet()
model model.fit(df)
STEP 4. Make Future Predictions:
#| label: python-make-forecast
# Create a dataframe for future predictions (next 12 months)
= model.make_future_dataframe(periods=12, freq='MS')
future = model.predict(future) forecast
STEP 5. Plotting the forecast:
#| label: python-plot-forecast
# Plot the forecast
= model.plot(forecast)
fig plt.show()
STEP 6. Plot Components of the Forecast:
This will show the trend, seasonality, and holiday effects in the forecast.
#| label: python-plot-components
# Plot the components of the forecast
= model.plot_components(forecast)
fig plt.show()
STEP 1. Load Required Packages:
#| label: r-required-packages
library(prophet)
STEP 2. Load and Transform Data:
#| label: r-load-data
# Load the AirPassengers dataset
<- read.csv("https://raw.githubusercontent.com/kassambara/datarium/refs/heads/main/data-raw/AirPassengersDf.csv")
air_passengers
# Convert the time values to a proper Date format
<- data.frame(
df ds = as.Date(air_passengers$Month),
y = as.numeric(air_passengers$Passengers)
)head(df)
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
The AirPassengers
dataset contains monthly data for passenger numbers.
STEP 3. Fit the Prophet Model:
#| label: r-prophet-fit
# Fit the Prophet model
<- prophet(df) model
Prophet will detect the monthly seasonality from the dataset and disable daily and weekly seasonality by default.
You can run prophet()
with weekly.seasonality = TRUE
or daily.seasonality = TRUE
to override this behavior.
STEP 4. Make Future Predictions:
The model has been trained on historical data from 1949 to 1960. We will now generate forecasts for the next 12 months (1961).
#| label: r-make-forecast
# Create a dataframe for future predictions (next 12 months)
<- make_future_dataframe(model, periods = 12, freq = "month")
future # Make predictions
<- predict(model, future) forecast
STEP 5. Plotting the forecast:
#| label: r-plot-forecast
# Plot the forecast
plot(model, forecast)
STEP 6. Plot Components of the Forecast:
This will show the trend, seasonality, and holiday effects in the forecast.
#| label: r-plot-components
# Plot the components of the forecast
prophet_plot_components(model, forecast)
Discussion
Data Preparation
Both examples leveraged the AirPassengers dataset, which contains monthly data for passenger numbers.
Model Fitting and Forecasting
Both examples use Prophet to fit a model and generate forecasts. The workflows are remarkably similar, which demonstrates how interoperability between languages can provide flexibility in choosing tools based on your specific needs.
Visualization
Each example concludes with a visualization of the forecast. In Python, we use Matplotlib via Prophet’s built-in plotting function, while in R, Prophet’s plot function creates a similar visual output.
Additional Resources
For those interested in exploring time series datasets from different fields, consider checking out the tsdl library on GitHub. It provides a diverse collection of time series data, which can be invaluable for testing and benchmarking forecasting models.
Conclusion
By comparing these side-by-side examples, you can see that Facebook Prophet offers a consistent approach to time series forecasting in both Python and R. This allows you to choose the environment that best fits your overall data science workflow without sacrificing functionality or performance.
Further Reading
Happy coding, and enjoy forecasting your time series data with Prophet!
Explore More Articles
Here are more articles from the same category to help you dive deeper into the topic.
Reuse
Citation
@online{kassambara2024,
author = {Kassambara, Alboukadel},
title = {Time {Series} {Analysis} in {Python} and {R}},
date = {2024-02-12},
url = {https://www.datanovia.com/learn/programming/r/cross-programming/time-series-analysis-in-python-and-r.html},
langid = {en}
}