How to Plot ACF and PACF in Python with statsmodels

Plot autocorrelation and partial autocorrelation with statsmodels, read the patterns, handle trends and seasonality, and customize the charts.

To plot the autocorrelation function (ACF) and partial autocorrelation function (PACF) in Python, use plot_acf() and plot_pacf() from statsmodels.graphics.tsaplots. The ACF shows how a series correlates with itself at each lag. The PACF shows the correlation at each lag after accounting for the shorter lags.

The examples use statsmodels 0.14.6.

Quick Example

This uses the yearly sunspot data included with statsmodels.

import matplotlib.pyplot as plt
import pandas as pd
import statsmodels.api as sm
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf

data = sm.datasets.sunspots.load_pandas().data
sunspots = pd.Series(data["SUNACTIVITY"].to_numpy(),
                     index=data["YEAR"].astype(int), name="sunspots")

fig, axes = plt.subplots(3, 1, figsize=(9, 8))
axes[0].plot(sunspots, color="#bc6c25", linewidth=1)
axes[0].set_title("Yearly sunspot activity, 1700 to 2008")
plot_acf(sunspots, lags=40, ax=axes[1])
plot_pacf(sunspots, lags=40, method="ywm", ax=axes[2])
for ax in axes[1:]:
    ax.set_xlabel("Lag (years)")
fig.tight_layout()
plt.show()

Sunspot time series with its ACF, which oscillates with peaks near lags 11, 22 and 32, and its PACF, with large spikes at lags 1 and 2

The ACF rises and falls in a wave, with peaks around lags 10 to 11 and 21 to 22, reflecting the solar cycle of roughly 11 years. The PACF has large spikes at lag 1 (0.82) and lag 2 (-0.68), then smaller ones at lags 6 to 9.

Passing ax= places each chart in your own subplot layout. Without it, each function creates a new figure.

What Do the Spikes and Shaded Band Mean?

  • Each spike is a correlation between -1 and 1 at one lag. Lag 0 is always 1. Hide it with zero=False.
  • The shaded band is a 95% confidence interval around zero, set by alpha=0.05. A spike outside it is unlikely under the null of no correlation.
  • With many lags, expect about 1 in 20 to fall outside by chance.
  • The ACF band widens with the lag because it uses Bartlett's formula by default (bartlett_confint=True). The PACF band is roughly constant at ±1.96/√n.

How to Read AR and MA Patterns

Simulated series show the textbook shapes. ArmaProcess takes the lag polynomials, so AR coefficients are entered with their signs flipped: ar=[1, -0.5, -0.3] means x[t] = 0.5*x[t-1] + 0.3*x[t-2] + noise.

import numpy as np
from statsmodels.tsa.arima_process import ArmaProcess

rng = np.random.default_rng(31)
n = 500
processes = {
    "White noise": ArmaProcess(ar=[1], ma=[1]),
    "AR(2)": ArmaProcess(ar=[1, -0.5, -0.3], ma=[1]),
    "MA(2)": ArmaProcess(ar=[1], ma=[1, 0.7, 0.5]),
    "ARMA(1,1)": ArmaProcess(ar=[1, -0.7], ma=[1, 0.5]),
}
series = {name: proc.generate_sample(n, distrvs=rng.standard_normal, burnin=200)
          for name, proc in processes.items()}

fig, axes = plt.subplots(4, 2, figsize=(10, 9.5), sharex=True, sharey=True)
for (name, x), (left, right) in zip(series.items(), axes):
    plot_acf(x, lags=20, zero=False, ax=left, title=f"{name}: ACF")
    plot_pacf(x, lags=20, zero=False, method="ywm", ax=right, title=f"{name}: PACF")
axes[0, 0].set_ylim(-0.5, 1)
fig.tight_layout()
plt.show()

ACF and PACF pairs for white noise, AR(2), MA(2) and ARMA(1,1). The AR(2) PACF cuts off after lag 2 and the MA(2) ACF cuts off after lag 2

Process ACF PACF
White noise No clear spikes No clear spikes
AR(p) Decays gradually Cuts off after lag p
MA(q) Cuts off after lag q Decays gradually
ARMA(p, q) Decays gradually Decays gradually

Real data is rarely this clean. Treat the cutoffs as a starting point for choosing model orders, then compare candidate models with a criterion such as AIC.

Remove Trend and Seasonality Before Reading the ACF

An ACF that stays high and falls very slowly usually means the series has a trend. Difference it first. This uses the Mauna Loa CO2 data in statsmodels, resampled to months:

co2 = sm.datasets.co2.load_pandas().data["co2"].resample("MS").mean().interpolate()
steps = {
    "Monthly CO2": co2,
    "First difference": co2.diff().dropna(),
    "First and seasonal difference": co2.diff().diff(12).dropna(),
}

fig, axes = plt.subplots(3, 2, figsize=(10, 8), gridspec_kw={"width_ratios": [1.2, 1]})
for (name, x), (left, right) in zip(steps.items(), axes):
    left.plot(x, color="#386641", linewidth=0.9)
    left.set_title(name)
    plot_acf(x, lags=48, zero=False, ax=right, title="ACF", markersize=3)
    right.set_ylim(-0.6, 1.05)
    right.set_xticks(range(0, 49, 12))
fig.tight_layout()
plt.show()

CO2 series before and after differencing with their ACFs: slow decay for the raw data, a repeating 12 month wave after one difference, and mostly small values with spikes at lags 1 and 12 after seasonal differencing

The raw series has an autocorrelation of 0.99 at lag 1. One difference removes the trend but leaves a 12-month wave (0.92 at lag 12). Adding a seasonal difference with diff(12) leaves two main spikes, at lag 1 (-0.30) and lag 12 (-0.41). Differencing leaves missing values at the start, and by default they turn every correlation into NaN, which is why the code calls dropna().

Customize the ACF Plot

color styles the markers, vlines_kwargs styles the stems, and auto_ylims=True fits the y-axis to the data. The shaded band is a collection on the axes that you can restyle afterwards:

from matplotlib.collections import FillBetweenPolyCollection

x = series["MA(2)"]

fig, ax = plt.subplots(figsize=(9, 3.8))
plot_acf(x, lags=30, zero=False, ax=ax, auto_ylims=True, color="#7209b7",
         vlines_kwargs={"colors": "#7209b7", "linewidth": 3})
for band in ax.findobj(FillBetweenPolyCollection):
    band.set_facecolor("#f72585")
    band.set_alpha(0.15)
ax.set(title="Autocorrelation of an MA(2) series", xlabel="Lag",
       ylabel="Correlation")
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
plt.show()

Purple ACF plot with thick stems and a pink confidence band, showing significant spikes at lags 1 and 2

FillBetweenPolyCollection was added in Matplotlib 3.10.

Get the ACF and PACF Values

acf() and pacf() return the numbers behind the charts. For the PACF, the defaults differ: pacf() uses method="ywadjusted", while plot_pacf() uses "ywm". Pass method explicitly so your numbers match the chart.

from statsmodels.tsa.stattools import acf, pacf

print(acf(sunspots, nlags=3).round(2))
print(pacf(sunspots, nlags=3, method="ywm").round(2))
[1.   0.82 0.45 0.04]
[ 1.    0.82 -0.68 -0.15]

Test Residuals with Ljung-Box

After fitting a model, its residuals should look like white noise. The Ljung-Box test checks several lags together:

from statsmodels.stats.diagnostic import acorr_ljungbox

print(acorr_ljungbox(series["White noise"], lags=[10, 20]).round(3))
    lb_stat  lb_pvalue
10   11.833      0.296
20   17.435      0.625

Large p-values give no evidence of remaining autocorrelation. For a fitted ARMA model, set model_df to the number of AR and MA terms.

For a quick ACF without statsmodels, pandas has pandas.plotting.autocorrelation_plot(), but it has no PACF counterpart.

Similar Topics