Skip to content
svgpettitt-u

Pettitt's change-point curve

Where does the series most likely change level, and is the change beyond chance?

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

How to read it

  1. Read the curve as the rank-sum contrast between before and after each date.
  2. The largest absolute value marks the most probable change.
  3. Crossing the dashed line means the change is beyond chance at that level.
  1. Callout 1: The largest |U|: the most likely change point.
  2. Callout 2: The significance limit.
  3. Callout 3: The date of the change.

Watch out

  • It looks for one change. Several changes or a smooth trend can also give a large peak.

Defaults

α for the reference line
0.05
The significance level for the reference line.
Range 0.001 to 0.2, step 0.005

Pinned in the code

  • U_t = Σ_{i≤t} Σ_{j>t} sgn(x_i − x_j) = 2 Σ_{i≤t} r_i − t(n+1) with mid-ranks, t = 1…n−1.
  • K = max |U_t| at the first maximising t (the last observation before the change), p ≈ 2 exp(−6K² / (n³ + n²)) — Pettitt's approximation, as trend::pettitt.test.
  • The dashed lines solve that approximation for |U| at p = α.
# Pettitt's change-point curve — Codesplash Chart Lab (recipe "pettitt-u")
# controls: alpha=0.05
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("pettitt-u-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 = "level"
ALPHA = 0.05
d = ordered(df, X, [Y])
v = d[Y].to_numpy(dtype=float)
n = len(v)
u = 2 * np.cumsum(stats.rankdata(v))[: n - 1] - np.arange(1, n) * (n + 1)  # U_t = Σ_{i≤t} Σ_{j>t} sgn(x_i − x_j)
K, loc = np.abs(u).max(), int(np.argmax(np.abs(u)))  # loc: last observation before the change (0-based)
p = min(1.0, 2 * np.exp(-6 * K**2 / (n**3 + n**2)))
crit = np.sqrt(-np.log(ALPHA / 2) * (n**3 + n**2) / 6)  # |U| where Pettitt's approximation gives p = α
t = time_of(d, X).iloc[: n - 1]
fig, ax = plt.subplots(figsize=(8, 4))
ax.axhspan(-crit, crit, color=GREY, alpha=0.3, lw=0)
ax.axhline(crit, color=REF, linestyle="--")
ax.axhline(-crit, color=REF, linestyle="--")
ax.plot(t, u, color=PALETTE[0], linewidth=1.6)
ax.scatter([t.iloc[loc]], [u[loc]], color="#ce5342", zorder=3)
ax.set_title(f"Pettitt K = {K:.0f}, p ≈ {p:.3g}; change after {t.iloc[loc]}", fontsize=10, loc="left")
ax.set_xlabel("month")
ax.set_ylabel("U_t")
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads pettitt-u-demo.csv · app theme from the optional codesplash helper