svgljung-box-p
Ljung–Box p-values by lag
Up to which lag is the series (or a model's residuals) indistinguishable from white noise?
How to read it
- Read each point as the test of all autocorrelations up to that lag.
- Points below the 5% line: some autocorrelation remains.
- For a model's residuals, you want points above the line.
- Callout 1: Below the line: not white noise up to this lag.
- Callout 2: The 5% reference line.
Watch out
- The points overlap in the lags they test, so they aren't independent results.
- A high p doesn't prove the residuals are white noise, only that this test didn't detect otherwise.
Defaults
- Max lag (0 = R default)
- 0
- How many lags to show; 0 uses R's rule based on the series length.
- Range 0 to 200, step 1
- Model degrees of freedom (p + q)
- 0
- For ARMA residuals: the χ² df become lag − fitdf.
- Range 0 to 20, step 1
Pinned in the code
- Q(L) = n(n + 2) Σ_{k=1…L} r_k²/(n − k), referred to χ²(L − fitdf) (R Box.test type = 'Ljung-Box'); r_k uses denominator n.
- Lags with df < 1 are not tested. Default max lag: max(⌊10 log₁₀ n⌋, fitdf + 5), capped at n − 2.
- Each point is a separate test of all lags up to L; they are strongly dependent, not independent evidence.
# Ljung–Box p-values by lag — Codesplash Chart Lab (recipe "ljung-box-p")
# controls: lagMax=0, fitdf=0
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
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("ljung-box-p-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_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 ordered(d, x, cols):
"""Rows with the needed values, sorted by the time column (stable); row order when there is none."""
d = d.dropna(subset=[c for c in cols if c] + ([x] if x else []))
return d.sort_values(x, kind="stable") if x else d
def time_of(d, x):
return d[x] if x else pd.Series(np.arange(1, len(d) + 1), index=d.index)
def ljung_box_by_lag(v, L, fitdf=0):
"""Q(k) = n(n+2) Σ_{j≤k} r_j²/(n−j) with r_j on denominator n; p from χ²(k − fitdf)."""
n = len(v)
x = v - v.mean()
den = (x * x).sum()
r = np.array([(x[j:] * x[:n - j]).sum() / den for j in range(1, L + 1)])
q = n * (n + 2) * np.cumsum(r * r / (n - np.arange(1, L + 1)))
df_ = np.arange(1, L + 1) - fitdf
p = np.where(df_ >= 1, stats.chi2.sf(q, np.maximum(df_, 1)), np.nan)
return np.arange(1, L + 1), q, p
X = None
Y = "residual"
LAG_MAX, FITDF = 0, 0 # 0 = max(⌊10 log₁₀ n⌋, fitdf + 5)
v = ordered(df, X, [Y])[Y].to_numpy(dtype=float)
n = len(v)
L = min(LAG_MAX, n - 2) if LAG_MAX > 0 else max(max(1, min(n - 1, int(np.floor(10 * np.log10(n))))), FITDF + 5)
lags, q, p = ljung_box_by_lag(v, max(1, L), FITDF)
fig, ax = plt.subplots(figsize=(7, 4))
ax.axhspan(0, 0.05, color="#ce5342", alpha=0.08, lw=0)
ax.axhline(0.05, color=REF, linestyle="--", linewidth=1)
ax.scatter(lags, p, c=np.where(p < 0.05, "#ce5342", PALETTE[0]), s=18, zorder=3)
ax.set_ylim(0, 1)
ax.set_xlabel("lags included")
ax.set_ylabel("Ljung–Box p-value")
plt.show()Needs pandas, numpy, matplotlib, scipy · reads ljung-box-p-demo.csv · app theme from the optional codesplash helper
# Ljung–Box p-values by lag — Codesplash Chart Lab (recipe "ljung-box-p")
# controls: lagMax=0, fitdf=0
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from scipy import stats
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("ljung-box-p-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_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 ordered(d, x, cols):
"""Rows with the needed values, sorted by the time column (stable); row order when there is none."""
d = d.dropna(subset=[c for c in cols if c] + ([x] if x else []))
return d.sort_values(x, kind="stable") if x else d
def time_of(d, x):
return d[x] if x else pd.Series(np.arange(1, len(d) + 1), index=d.index)
def ljung_box_by_lag(v, L, fitdf=0):
"""Q(k) = n(n+2) Σ_{j≤k} r_j²/(n−j) with r_j on denominator n; p from χ²(k − fitdf)."""
n = len(v)
x = v - v.mean()
den = (x * x).sum()
r = np.array([(x[j:] * x[:n - j]).sum() / den for j in range(1, L + 1)])
q = n * (n + 2) * np.cumsum(r * r / (n - np.arange(1, L + 1)))
df_ = np.arange(1, L + 1) - fitdf
p = np.where(df_ >= 1, stats.chi2.sf(q, np.maximum(df_, 1)), np.nan)
return np.arange(1, L + 1), q, p
X = None
Y = "residual"
LAG_MAX, FITDF = 0, 0
v = ordered(df, X, [Y])[Y].to_numpy(dtype=float)
n = len(v)
L = min(LAG_MAX, n - 2) if LAG_MAX > 0 else max(max(1, min(n - 1, int(np.floor(10 * np.log10(n))))), FITDF + 5)
lags, q, p = ljung_box_by_lag(v, max(1, L), FITDF)
fig = go.Figure(go.Scatter(x=lags, y=p, mode="markers", marker=dict(color=np.where(p < 0.05, "#ce5342", PALETTE[0]), size=8), customdata=q,
hovertemplate="lags 1–%{x}: Q = %{customdata:.2f}, p = %{y:.4f}<extra></extra>"))
fig.add_hline(y=0.05, line=dict(color=REF, dash="dash"))
fig.update_layout(xaxis_title="lags included", yaxis_title="Ljung–Box p-value", yaxis_range=[0, 1])
fig.show()Needs pandas, numpy, plotly, scipy · reads ljung-box-p-demo.csv · app theme from the optional codesplash helper
# Ljung–Box p-values by lag — Codesplash Chart Lab (recipe "ljung-box-p")
# controls: lagMax=0, fitdf=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("ljung-box-p-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
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
ordered <- function(d, x, cols) {
keep <- stats::complete.cases(d[, c(cols, x), drop = FALSE])
d <- d[keep, , drop = FALSE]
if (!is.null(x)) d[order(d[[x]]), , drop = FALSE] else d
}
time_of <- function(d, x) if (is.null(x)) seq_len(nrow(d)) else d[[x]]
x_col <- NULL
y_col <- "residual"
LAG_MAX <- 0
FITDF <- 0
v <- ordered(df, x_col, y_col)[[y_col]]
n <- length(v)
L <- max(1, if (LAG_MAX > 0) min(LAG_MAX, n - 2) else max(max(1, min(n - 1, floor(10 * log10(n)))), FITDF + 5))
lb <- do.call(rbind, lapply(seq_len(L), function(k) {
b <- stats::Box.test(v, lag = k, type = "Ljung-Box", fitdf = if (k - FITDF >= 1) FITDF else 0)
data.frame(lag = k, q = unname(b$statistic), p = if (k - FITDF >= 1) b$p.value else NA)
}))
p <- ggplot(lb[!is.na(lb$p), ], aes(lag, p)) +
annotate("rect", xmin = -Inf, xmax = Inf, ymin = 0, ymax = 0.05, fill = "#ce5342", alpha = 0.08) +
geom_hline(yintercept = 0.05, colour = ref_col, linetype = "dashed") +
geom_point(aes(colour = p < 0.05), size = 1.8) + scale_colour_manual(values = c("FALSE" = cs_cat[1], "TRUE" = "#ce5342"), guide = "none") +
coord_cartesian(ylim = c(0, 1)) + labs(x = "lags included", y = "Ljung–Box p-value") + theme_cs
print(p)Needs ggplot2 · reads ljung-box-p-demo.csv · app theme from the optional codesplashr helper