Seasonal Decomposition in Python: Plot Trend, Seasonality and Residuals

Split a time series into trend, seasonal and residual parts with statsmodels seasonal_decompose and STL, choose additive or multiplicative, handle outliers and plot the components.

To decompose a time series in Python, pass a pandas Series with a regular frequency to seasonal_decompose(series, model="multiplicative", period=12) from statsmodels.tsa.seasonal and call .plot() on the result. You get four panels: the observed data, the trend, the repeating seasonal pattern and the residual that neither explains. For data with outliers or a seasonal pattern that changes over time, use STL instead.

This post was run with statsmodels 0.14 and pandas 3.1. Install with pip install statsmodels.

Quick Example

The data is eight years of simulated monthly bike rentals for a city bike-share scheme: a rising trend, a summer peak that grows with the trend, and noise. One month (March 2023) is a storm that cut rentals by about 40%.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.seasonal import seasonal_decompose

rng = np.random.default_rng(8)
months = pd.date_range("2018-01-01", periods=96, freq="MS")
trend = 4_000 + 55 * np.arange(96)
season = 1 + 0.45 * np.sin(2 * np.pi * (months.month - 4) / 12)   # peaks in July
rentals = pd.Series(trend * season * rng.normal(1, 0.04, 96), index=months, name="rentals")
rentals.loc["2023-03-01"] *= 0.6                                    # a storm month
rentals = rentals.round()

result = seasonal_decompose(rentals, model="multiplicative", period=12)
result.plot()
plt.show()

Four stacked panels showing monthly bike rentals, a rising trend line, a repeating yearly seasonal pattern and the residuals

The trend climbs steadily from about 4,300 to 8,800 rentals a month, and the seasonal panel repeats the same yearly shape. The residual panel sits close to 1 (multiplicative residuals are ratios), apart from one point at 0.69 in March 2023: that month came in about 31% below what the trend and season predicted, which is the storm. The first and last six months of the trend are blank, because the centered moving average needs six months on each side.

What do the components mean?

The result object holds each part as a pandas Series: result.observed, result.trend, result.seasonal and result.resid. With model="multiplicative" they multiply back to the original (observed = trend * seasonal * resid), so the seasonal part is an index around 1. Averaging it by calendar month gives the typical month effect:

seasonal_index = result.seasonal.groupby(result.seasonal.index.month).first()
print(seasonal_index.round(2).to_string())
print(result.trend.isna().sum(), "NaNs in the trend")
1     0.56
2     0.61
3     0.71
4     0.99
5     1.23
6     1.39
7     1.43
8     1.35
9     1.27
10    1.04
11    0.79
12    0.62
12 NaNs in the trend

July is the peak at 1.43, meaning rentals run 43% above the trend, and January is the low at 0.56, or 44% below it. The trend has 12 NaNs, six at each end. Pass extrapolate_trend="freq" to fill those with a linear fit if you need values there.

Additive or multiplicative?

Use model="additive" when the seasonal swings stay the same size as the level changes (observed = trend + seasonal + resid), and "multiplicative" when they grow with it. A quick check is to decompose with both and compare the residuals: the right model leaves residuals with no leftover pattern.

additive = seasonal_decompose(rentals, model="additive", period=12)

fig, axes = plt.subplots(1, 2, figsize=(11, 3.6), sharey=False)
axes[0].plot(additive.resid, color="#e76f51")
axes[0].axhline(0, color="gray", lw=0.8)
axes[0].set_title("Additive residuals (rentals)")
axes[1].plot(result.resid, color="#2a9d8f")
axes[1].axhline(1, color="gray", lw=0.8)
axes[1].set_title("Multiplicative residuals (ratio)")
fig.tight_layout()
plt.show()

Two residual plots: additive residuals swing in a repeating yearly wave while multiplicative residuals scatter evenly around 1

The multiplicative residuals scatter evenly around 1 apart from the storm month. The additive residuals (left) swing in a wave that repeats each year, because a fixed seasonal amount cannot fit swings that grow with the level: it is too big in the early years and too small in the later ones. A residual plot with a visible pattern is the sign you picked the wrong model.

How do I handle outliers with STL?

seasonal_decompose uses a moving average, so one extreme month leaks into the trend and the seasonal pattern. STL (seasonal-trend decomposition using LOESS) can be made robust to outliers with robust=True, and it lets the seasonal pattern change slowly over the years. It is additive only, so take the log first if the seasonality is multiplicative:

from statsmodels.tsa.seasonal import STL

stl = STL(np.log(rentals), period=12, robust=True).fit()
stl.plot()
plt.show()

STL decomposition of the log of monthly rentals showing a smooth trend, a seasonal pattern and one large negative residual in March 2023

The trend is smooth, the seasonal pattern repeats, and the storm shows up as a single residual of about −0.44 in March 2023 (a factor of exp(-0.44) = 0.65, so roughly 35% below expectation). robust=True downweights that month so it stays in the residual instead of bending the trend and seasonal parts. The residuals are on the log scale here: add np.exp() to the components to get back to rentals. seasonal=13 (it must be odd and at least 3) sets how quickly the seasonal pattern may change, with larger values forcing it to stay closer to constant.

Plot the components yourself

result.plot() draws small panels with no styling. For a report, build the figure from the component Series. This one also adds the seasonally adjusted series (the data with the seasonal part divided out), which is the line to look at if you want to know whether demand is really rising:

adjusted = rentals / result.seasonal

fig, axes = plt.subplots(3, 1, figsize=(9, 8), sharex=True)
axes[0].plot(rentals, color="#9aa5b1", label="Observed")
axes[0].plot(result.trend, color="#264653", lw=2.5, label="Trend")
axes[0].legend(loc="upper left")
axes[1].plot(adjusted, color="#8d6a9f")
axes[1].set_title("Seasonally adjusted")
axes[2].bar(result.seasonal.index, result.seasonal - 1, width=25, color="#2a9d8f")
axes[2].set_title("Seasonal effect (ratio minus 1)")
fig.tight_layout()
plt.show()

Three panels: observed rentals with a trend line, the seasonally adjusted series and bars for the seasonal effect

The observed line rises with the seasons, but the seasonally adjusted line rises almost steadily from about 3,700 to 9,100 and flattens a little after 2024. The storm shows up as a lone dip to roughly 5,000 in March 2023 once the season is removed, so you can tell it was a one-off and not part of the pattern.

How strong is the seasonality?

A single number helps decide whether decomposing is worth it. The strength of seasonality is 1 - Var(resid) / Var(seasonal + resid) on the additive scale, which runs from 0 (none) to 1 (the seasonal part explains everything). The same formula works for trend strength:

def strength(part, resid):
    return max(0, 1 - resid.var() / (part + resid).var())

print("seasonal strength:", round(strength(stl.seasonal, stl.resid), 3))
print("trend strength:   ", round(strength(stl.trend, stl.resid), 3))
seasonal strength: 0.973
trend strength:    0.949

seasonal_decompose vs STL

seasonal_decompose STL
Model Additive or multiplicative Additive (use np.log for multiplicative)
Seasonal pattern Identical every cycle Can change slowly (seasonal= smoothing)
Outliers Leak into trend and seasonal robust=True downweights them
Trend at the ends NaN for half a period (or extrapolate_trend) Defined everywhere
Missing values Not allowed Not allowed
Best for A quick look Reporting, messy data

Practical Tips

  • The index needs a frequency. With a DatetimeIndex that pandas can infer (MS, D), period is picked up automatically, but pass period= explicitly. Use 7 for daily data with a weekly cycle and 12 for monthly data.
  • You need at least two full cycles. Fewer than 2 * period observations raises a ValueError.
  • Fill gaps first. Neither function accepts NaN. Resample, then fill them with rentals.interpolate() (or asfreq("MS") first to expose missing rows).
  • Check the residuals. If they still show a pattern, plot them with an ACF plot.
  • Two cycles at once (daily and yearly) need MSTL, also in statsmodels.tsa.seasonal.

Similar Topics