svgacf-plot
ACF / PACF (precomputed)
Is a series (or a model's residuals) autocorrelated, and at which lags?
How to read it
- Read bars outside the band as autocorrelation beyond noise.
- For model residuals, you want nothing outside.
- A spike at the seasonal lag means the season is not fully modelled.
- Callout 1: A bar beyond the band, at the seasonal lag.
- Callout 2: The band: the range for white noise.
- Callout 3: The same lag on the partial side.
Watch out
- About 1 lag in 20 pokes out by chance.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
- Correlations come from the engine (statsmodels acf/pacf ↔ R acf/pacf on the residuals or the series); the band is the engine's ±1.96/√n white-noise bound when sent.
- Use the time-series family's "acf" recipe to compute these from raw data instead.
# ACF / PACF (precomputed) — Codesplash Chart Lab (recipe "acf-plot")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
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-plot-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["kind"] = pd.Categorical(df["kind"].astype("string"), categories=["acf", "pacf"])
_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 levels_of(s):
"""Declared level order (categoricals), else order of first appearance."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [v for v in s.cat.categories if (s == v).any()]
return list(dict.fromkeys(s.dropna().astype(str)))
LAG = "lag (months)"
ACF = "correlation"
B = "bound"
KIND = "kind"
d = df.dropna(subset=[LAG, ACF]).sort_values(LAG)
kinds = levels_of(d[KIND]) if KIND else [None]
fig, axes = plt.subplots(1, len(kinds), figsize=(4.2 * len(kinds) + 1, 3.8), squeeze=False, sharey=True)
for ax, k in zip(axes[0], kinds): # ACF and PACF side by side
g = d if k is None else d[d[KIND].astype(str) == str(k)]
bound = float(g[B].iloc[0]) if B else None
if bound is not None:
ax.axhspan(-bound, bound, color=GREY, alpha=0.4, lw=0) # ±1.96/√n
out = (g[ACF].abs() > bound) if bound is not None else pd.Series(False, index=g.index)
cols = np.where(out, "#ce5342", PALETTE[0])
ax.vlines(g[LAG], 0, g[ACF], colors=cols, linewidth=2)
ax.scatter(g[LAG], g[ACF], c=cols, s=14, zorder=3)
ax.axhline(0, color="grey", linewidth=0.8)
ax.set_title(str(k).upper() if k is not None else ACF, fontsize=10)
ax.set_xlabel(LAG)
axes[0, 0].set_ylabel(ACF)
fig.tight_layout()
plt.show()Needs pandas, numpy, matplotlib · reads acf-plot-demo.csv · app theme from the optional codesplash helper
# ACF / PACF (precomputed) — Codesplash Chart Lab (recipe "acf-plot")
# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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-plot-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["kind"] = pd.Categorical(df["kind"].astype("string"), categories=["acf", "pacf"])
_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 levels_of(s):
"""Declared level order (categoricals), else order of first appearance."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [v for v in s.cat.categories if (s == v).any()]
return list(dict.fromkeys(s.dropna().astype(str)))
LAG = "lag (months)"
ACF = "correlation"
B = "bound"
KIND = "kind"
d = df.dropna(subset=[LAG, ACF]).sort_values(LAG)
kinds = levels_of(d[KIND]) if KIND else [None]
fig = make_subplots(rows=1, cols=len(kinds), shared_yaxes=True, subplot_titles=[str(k).upper() if k is not None else ACF for k in kinds])
for i, k in enumerate(kinds, start=1):
g = d if k is None else d[d[KIND].astype(str) == str(k)]
bound = float(g[B].iloc[0]) if B else None
if bound is not None:
fig.add_hrect(y0=-bound, y1=bound, fillcolor=GREY, opacity=0.4, line_width=0, row=1, col=i)
out = (g[ACF].abs() > bound) if bound is not None else pd.Series(False, index=g.index)
fig.add_bar(x=g[LAG], y=g[ACF], width=0.25, marker_color=np.where(out, "#ce5342", PALETTE[0]), showlegend=False, row=1, col=i)
fig.update_xaxes(title_text=LAG, row=1, col=i)
fig.update_yaxes(title_text=ACF, row=1, col=1)
fig.show()Needs pandas, numpy, plotly · reads acf-plot-demo.csv · app theme from the optional codesplash helper
# ACF / PACF (precomputed) — Codesplash Chart Lab (recipe "acf-plot")
# controls: defaults
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-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["kind"]] <- factor(df[["kind"]], levels = c("acf", "pacf"))
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
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
lag_col <- "lag (months)"
acf_col <- "correlation"
b_col <- "bound"
kind_col <- "kind"
d <- df[!is.na(df[[lag_col]]) & !is.na(df[[acf_col]]), ]
d <- data.frame(lag = d[[lag_col]], r = d[[acf_col]], b = if (is.null(b_col)) NA_real_ else d[[b_col]],
kind = if (is.null(kind_col)) acf_col else factor(toupper(as.character(d[[kind_col]])), levels = toupper(levels_of(d[[kind_col]]))))
d$out <- !is.na(d$b) & abs(d$r) > d$b # outside the ±1.96/√n band
bands <- unique(d[!is.na(d$b), c("kind", "b")])
p <- ggplot(d, aes(lag, r)) +
{ if (nrow(bands)) geom_rect(data = bands, aes(xmin = -Inf, xmax = Inf, ymin = -b, ymax = b), inherit.aes = FALSE, fill = grey_col, alpha = 0.4) } +
geom_hline(yintercept = 0, colour = "grey50") + geom_segment(aes(xend = lag, y = 0, yend = r, colour = out), linewidth = 0.9) +
geom_point(aes(colour = out), size = 1.4) + scale_colour_manual(values = c("FALSE" = cs_cat[1], "TRUE" = "#ce5342"), guide = "none") +
facet_wrap(~kind, nrow = 1) + labs(x = lag_col, y = acf_col) + theme_cs
print(p)Needs ggplot2 · reads acf-plot-demo.csv · app theme from the optional codesplashr helper