svgbuishand-cusum
Buishand cumulative deviations
Does the running sum of deviations from the mean bend sharply — a shift in level?
How to read it
- Read the curve as the running sum of deviations from the overall mean.
- A sharp tent peaks at a level shift.
- A smooth arch suggests a gradual trend instead.
- Callout 1: The peak: the most likely point of the shift.
- Callout 2: It always returns to zero at the end.
Watch out
- The curve must start and end at zero, so a hump isn't evidence on its own. Use the test's p-value.
Defaults
No settings: the chart draws one way.
Pinned in the code
- S_k = Σ_{i≤k} (x_i − x̄) / s for k = 1…n with the sample sd s (n − 1), as trend::br.test / bu.test; Buishand (1982) divides by n.
- R/√n = (max S − min S)/√n over k = 0…n (S_0 = 0); U = Σ_{k<n} S_k² / (n(n+1)). The marker sits at the largest |S_k|.
- p-values for R and U come from Monte Carlo in the analysis (normal null); the chart shows the statistics only.
# Buishand cumulative deviations — Codesplash Chart Lab (recipe "buishand-cusum")
# 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("buishand-cusum-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 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)
X = "month"
Y = "rainfall index"
d = ordered(df, X, [Y])
v = d[Y].to_numpy(dtype=float)
n = len(v)
s = np.cumsum(v - v.mean()) / v.std(ddof=1) # S_k / s, sample sd as trend::br.test
rng_stat = (max(0, s.max()) - min(0, s.min())) / np.sqrt(n)
U = (s[: n - 1] ** 2).sum() / (n * (n + 1))
loc = int(np.argmax(np.abs(s[: n - 1])))
t = time_of(d, X)
fig, ax = plt.subplots(figsize=(8, 4))
ax.axhline(0, color="grey", linewidth=0.8)
ax.plot(t, s, color=PALETTE[0], linewidth=1.6)
ax.axvline(t.iloc[loc], color=REF, linestyle=":", linewidth=1)
ax.scatter([t.iloc[loc]], [s[loc]], color="#ce5342", zorder=3)
ax.set_title(f"R/√n = {rng_stat:.3f}, U = {U:.3f}; largest deviation after {t.iloc[loc]}", fontsize=10, loc="left")
ax.set_xlabel("month")
ax.set_ylabel("Σ (x − x̄) / s")
plt.show()Needs pandas, numpy, matplotlib · reads buishand-cusum-demo.csv · app theme from the optional codesplash helper
# Buishand cumulative deviations — Codesplash Chart Lab (recipe "buishand-cusum")
# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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("buishand-cusum-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 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)
X = "month"
Y = "rainfall index"
d = ordered(df, X, [Y])
v = d[Y].to_numpy(dtype=float)
n = len(v)
s = np.cumsum(v - v.mean()) / v.std(ddof=1)
rng_stat = (max(0, s.max()) - min(0, s.min())) / np.sqrt(n)
U = (s[: n - 1] ** 2).sum() / (n * (n + 1))
loc = int(np.argmax(np.abs(s[: n - 1])))
t = time_of(d, X)
fig = go.Figure(go.Scatter(x=t, y=s, mode="lines", line=dict(color=PALETTE[0])))
fig.add_scatter(x=[t.iloc[loc]], y=[s[loc]], mode="markers", marker=dict(color="#ce5342", size=9))
fig.add_hline(y=0, line=dict(color="grey"))
fig.update_layout(title=f"R/√n = {rng_stat:.3f}, U = {U:.3f}", xaxis_title="month", yaxis_title="Σ (x − x̄) / s", showlegend=False)
fig.show()Needs pandas, numpy, plotly · reads buishand-cusum-demo.csv · app theme from the optional codesplash helper
# Buishand cumulative deviations — Codesplash Chart Lab (recipe "buishand-cusum")
# 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("buishand-cusum-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
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 <- "month"
y_col <- "rainfall index"
d <- ordered(df, x_col, y_col)
v <- d[[y_col]]
n <- length(v)
s <- cumsum(v - mean(v)) / stats::sd(v) # sample sd, as trend::br.test
rng_stat <- (max(0, s) - min(0, s)) / sqrt(n)
U <- sum(s[1:(n - 1)]^2) / (n * (n + 1))
loc <- which.max(abs(s[1:(n - 1)]))
bs <- data.frame(t = time_of(d, x_col), s = s)
p <- ggplot(bs, aes(t, s)) + geom_hline(yintercept = 0, colour = "grey50") + geom_line(colour = cs_cat[1]) +
geom_vline(xintercept = bs$t[loc], colour = ref_col, linetype = "dotted") + geom_point(data = bs[loc, ], colour = "#ce5342", size = 2.5) +
labs(x = "month", y = "Σ (x − x̄) / s", title = sprintf("R/√n = %.3f, U = %.3f", rng_stat, U)) + theme_cs
print(p)Needs ggplot2 · reads buishand-cusum-demo.csv · app theme from the optional codesplashr helper