svgacf
ACF & PACF
Is the series autocorrelated, and at which lags (seasonality, AR order)?
How to read it
- Read each bar as the correlation between the series and itself at that lag.
- Bars outside the dashed band are larger than noise would usually give.
- Slowly fading ACF suggests a trend; a spike at the seasonal lag suggests a season; PACF cut-offs suggest an AR order.
- Callout 1: Lag 1: the correlation with the previous value.
- Callout 2: Dashed band: the range for white noise.
- 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
# ACF & PACF — Codesplash Chart Lab (recipe "acf")
# controls: show=both, lagMax=0
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from scipy.stats import norm
from plotly.subplots import make_subplots
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 px.colors.qualitative.Plotly
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))
panels = []
panels.append(("ACF", np.arange(L + 1), acf(v, L)))
panels.append(("PACF", np.arange(1, L + 1), pacf(v, L)))
fig = make_subplots(rows=len(panels), cols=1, shared_xaxes=True, subplot_titles=[p[0] for p in panels])
for i, (name, lags, vals) in enumerate(panels):
fig.add_bar(x=lags, y=vals, width=0.25, marker_color=[GREY if k == 0 else PALETTE[0] for k in lags], showlegend=False, row=i + 1, col=1)
for b in (bound, -bound):
fig.add_hline(y=b, line=dict(color=REF, dash="dash", width=1), row=i + 1, col=1)
fig.update_layout(title=f"Autocorrelation of demand (n = {len(v)})", height=260 * len(panels))
fig.show()Needs pandas, numpy, plotly, scipy · reads acf-demo.csv · app theme from the optional codesplash helper
# ACF & PACF — Codesplash Chart Lab (recipe "acf")
# controls: show=both, lagMax=0
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("acf-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["month"]] <- as.POSIXct(df[["month"]], tz = "UTC")
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
d <- df[!is.na(df[["month"]]) & !is.na(df[["demand"]]), , drop = FALSE]
d <- d[order(d[["month"]]), , drop = FALSE] # lags count observations, not calendar time
v <- d[["demand"]]
L <- max(1, min(length(v) - 1, floor(10 * log10(length(v))))) # R default
bound <- stats::qnorm(0.975) / sqrt(length(v)) # ±qnorm(0.975)/√n white-noise limits
panels <- rbind(
data.frame(panel = "ACF", lag = 0:L, value = as.numeric(stats::acf(v, lag.max = L, plot = FALSE, demean = TRUE)$acf)),
data.frame(panel = "PACF", lag = 1:L, value = as.numeric(stats::pacf(v, lag.max = L, plot = FALSE)$acf)) # Durbin–Levinson
)
panels$panel <- factor(panels$panel, levels = c("ACF", "PACF"))
p <- ggplot(panels, aes(lag, value)) +
geom_hline(yintercept = 0, colour = ref_col) +
geom_hline(yintercept = c(-bound, bound), colour = ref_col, linetype = "dashed") +
geom_segment(aes(xend = lag, yend = 0, colour = lag == 0), linewidth = 1, show.legend = FALSE) +
scale_colour_manual(values = c(`FALSE` = cs_cat[1], `TRUE` = grey_col)) + # lag 0 = 1 in grey
facet_wrap(~panel, ncol = 1) +
labs(x = "lag (observations)", y = NULL, title = sprintf("Autocorrelation of demand (n = %d)", length(v))) +
theme_cs
print(p)Needs ggplot2 · reads acf-demo.csv · app theme from the optional codesplashr helper
-- ACF & PACF — Codesplash Chart Lab (recipe "acf")
-- controls: show=both, lagMax=0
-- ACF (R acf, denominator n at every lag) by a self-join on the time order; PACF needs the client
WITH s AS (
SELECT row_number() OVER (ORDER BY "month") AS i, "demand"::DOUBLE AS v
FROM read_csv('acf-demo.csv') WHERE "demand" IS NOT NULL AND "month" IS NOT NULL
),
m AS (SELECT avg(v) AS mean, count(*) AS n FROM s),
d AS (SELECT i, v - mean AS dev FROM s, m),
tot AS (SELECT sum(dev * dev) AS c0 FROM d),
lags AS (SELECT i - 1 AS k FROM s, m WHERE i - 1 <= greatest(1, least(n - 1, floor(10 * log10(n))))::INTEGER)
SELECT lags.k AS lag, sum(a.dev * b.dev) / any_value(tot.c0) AS acf,
1.959963984540054 / sqrt(any_value(m.n)) AS bound -- qnorm(0.975)/√n
FROM lags
JOIN d a ON true
JOIN d b ON b.i = a.i + lags.k
CROSS JOIN tot
CROSS JOIN m
GROUP BY lags.k
ORDER BY lags.k;Needs duckdb · reads acf-demo.csv