Skip to content
svgbuishand-cusum

Buishand cumulative deviations

Does the running sum of deviations from the mean bend sharply — a shift in level?

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

How to read it

  1. Read the curve as the running sum of deviations from the overall mean.
  2. A sharp tent peaks at a level shift.
  3. A smooth arch suggests a gradual trend instead.
  1. Callout 1: The peak: the most likely point of the shift.
  2. 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