Skip to content
svgacf

ACF & PACF

Is the series autocorrelated, and at which lags (seasonality, AR order)?

Demo data · seed 20261101 · 144 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Read each bar as the correlation between the series and itself at that lag.
  2. Bars outside the dashed band are larger than noise would usually give.
  3. Slowly fading ACF suggests a trend; a spike at the seasonal lag suggests a season; PACF cut-offs suggest an AR order.
  1. Callout 1: Lag 1: the correlation with the previous value.
  2. Callout 2: Dashed band: the range for white noise.
  3. Callout 3: PACF: the correlation left after shorter lags are accounted for.

Watch out

  • With many lags, about 1 in 20 bars pokes out by chance.

Defaults

Panels
ACF and PACF
Which panels to show.
Also: ACF only · PACF only
Max lag (0 = R default)
0
How many lags to show; 0 uses R's rule based on the series length.
Range 0 to 120, step 1

Pinned in the code

  • ACF (R `acf`): r_k = Σ(x_t − x̄)(x_{t+k} − x̄) / Σ(x_t − x̄)², denominator n at every lag (biased, positive-definite estimator); lag 0 = 1 is drawn in grey.
  • PACF (R `pacf`): Durbin–Levinson recursion on the ACF; starts at lag 1.
  • Bounds: ±qnorm(0.975)/√n — approximate 95% limits under white noise (not for MA-model identification beyond lag 1).
  • Default max lag: min(n − 1, ⌊10·log₁₀ n⌋) (R). Missing values are dropped; rows are sorted by the time column; lags count observations.
# ACF & PACF — Codesplash Chart Lab (recipe "acf")
# controls: show=both, lagMax=0
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import norm

try:
    import codesplash as cs  # optional: the app's chart theme
except ImportError:
    cs = None
if cs:
    cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]

df = pd.read_csv("acf-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["month"] = pd.to_datetime(df["month"])

_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"])  # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"])  # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
def acf(v, max_lag):
    """R acf: r_k = Σ(x_t − x̄)(x_{t+k} − x̄) / Σ(x_t − x̄)², denominator n at every lag."""
    d = v - v.mean()
    c0 = (d * d).sum()
    return np.array([(d[: len(d) - k] * d[k:]).sum() / c0 for k in range(max_lag + 1)])

def pacf(v, max_lag):
    """R pacf: Durbin–Levinson recursion on the ACF (lags 1…max_lag)."""
    r = acf(v, max_lag)
    out, phi = [], np.array([])
    for k in range(1, max_lag + 1):
        num = r[k] - (phi * r[k - 1:0:-1]).sum() if k > 1 else r[1]
        den = 1 - (phi * r[1:k]).sum() if k > 1 else 1.0
        pkk = num / den
        phi = np.r_[phi - pkk * phi[::-1], pkk]
        out.append(pkk)
    return np.array(out)

d = df.dropna(subset=["month", "demand"]).sort_values("month", kind="stable")  # lags count observations, not calendar time
v = d["demand"].to_numpy(dtype=float)
L = max(1, min(len(v) - 1, int(np.floor(10 * np.log10(len(v))))))  # R default
bound = norm.ppf(0.975) / np.sqrt(len(v))  # ±qnorm(0.975)/√n white-noise limits
panels = []
panels.append(("ACF", np.arange(L + 1), acf(v, L)))
panels.append(("PACF", np.arange(1, L + 1), pacf(v, L)))
fig, axes = plt.subplots(len(panels), 1, figsize=(8, 2.6 * len(panels)), squeeze=False, sharex=True)
for ax, (name, lags, vals) in zip(axes[:, 0], panels):
    colours = [GREY if k == 0 else PALETTE[0] for k in lags]  # lag 0 = 1 in grey
    ax.vlines(lags, 0, vals, colors=colours, linewidth=2)
    ax.axhline(0, color=REF, linewidth=0.8)
    ax.axhline(bound, color=REF, linestyle="--", linewidth=0.8)
    ax.axhline(-bound, color=REF, linestyle="--", linewidth=0.8)
    ax.set_ylabel(name)
axes[-1, 0].set_xlabel("lag (observations)")
fig.suptitle(f"Autocorrelation of demand (n = {len(v)})", fontsize=10)
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads acf-demo.csv · app theme from the optional codesplash helper