Time Series Analysis in Python and R

Side-by-Side Tutorial Using Prophet

Compare time series forecasting workflows using Facebook Prophet in both Python and R. This tutorial provides side-by-side examples to help you understand how to load data, fit models, and visualize forecasts in each environment.

Programming
Author
Affiliation
Published

February 12, 2024

Modified

March 11, 2025

Keywords

time series analysis Python R, Prophet tutorial, Python Prophet, R Prophet, forecasting in Python, forecasting in R

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
air_passengers = pd.read_csv("https://raw.githubusercontent.com/kassambara/datarium/refs/heads/main/data-raw/AirPassengersDf.csv")

# Convert the time values to a proper Date format
df = pd.DataFrame({
    '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
Note

The AirPassengers dataset contains monthly data for passenger numbers.

STEP 3. Fit the Prophet Model:

#| label: python-prophet-fit
# Fit the Prophet model
model = Prophet()
model.fit(df)

STEP 4. Make Future Predictions:

#| label: python-make-forecast
# Create a dataframe for future predictions (next 12 months)
future = model.make_future_dataframe(periods=12, freq='MS')
forecast = model.predict(future)

STEP 5. Plotting the forecast:

#| label: python-plot-forecast
# Plot the forecast
fig = model.plot(forecast)
plt.show()

Python Prophet Forecast

STEP 6. Plot Components of the Forecast:

Note

This will show the trend, seasonality, and holiday effects in the forecast.

#| label: python-plot-components
# Plot the components of the forecast
fig = model.plot_components(forecast)
plt.show()

Python Prophet Forecast Components

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
air_passengers <- read.csv("https://raw.githubusercontent.com/kassambara/datarium/refs/heads/main/data-raw/AirPassengersDf.csv")

# Convert the time values to a proper Date format
df <- data.frame(
  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
Note

The AirPassengers dataset contains monthly data for passenger numbers.

STEP 3. Fit the Prophet Model:

#| label: r-prophet-fit
# Fit the Prophet model
model <- prophet(df)
Note

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)
future <- make_future_dataframe(model, periods = 12, freq = "month")
# Make predictions
forecast <- predict(model, future)

STEP 5. Plotting the forecast:

#| label: r-plot-forecast
# Plot the forecast
plot(model, forecast)

R Prophet Forecast

STEP 6. Plot Components of the Forecast:

Note

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)

R Prophet Forecast Components

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!

Back to top

Reuse

Citation

BibTeX 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}
}
For attribution, please cite this work as:
Kassambara, Alboukadel. 2024. “Time Series Analysis in Python and R.” February 12, 2024. https://www.datanovia.com/learn/programming/r/cross-programming/time-series-analysis-in-python-and-r.html.