svgpettitt-u
Pettitt's change-point curve
Where does the series most likely change level, and is the change beyond chance?
How to read it
- Read the curve as the rank-sum contrast between before and after each date.
- The largest absolute value marks the most probable change.
- Crossing the dashed line means the change is beyond chance at that level.
- Callout 1: The largest |U|: the most likely change point.
- Callout 2: The significance limit.
- 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
# Pettitt's change-point curve — Codesplash Chart Lab (recipe "pettitt-u")
# controls: alpha=0.05
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("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)
K, loc = np.abs(u).max(), int(np.argmax(np.abs(u)))
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)
t = time_of(d, X).iloc[: n - 1]
fig = go.Figure(go.Scatter(x=t, y=u, mode="lines", line=dict(color=PALETTE[0])))
fig.add_hrect(y0=-crit, y1=crit, fillcolor=GREY, opacity=0.3, line_width=0)
fig.add_scatter(x=[t.iloc[loc]], y=[u[loc]], mode="markers", marker=dict(color="#ce5342", size=9), showlegend=False)
fig.update_layout(title=f"Pettitt K = {K:.0f}, p ≈ {p:.3g}", xaxis_title="month", yaxis_title="U_t", showlegend=False)
fig.show()Needs pandas, numpy, plotly, scipy · reads pettitt-u-demo.csv · app theme from the optional codesplash helper
# Pettitt's change-point curve — Codesplash Chart Lab (recipe "pettitt-u")
# controls: alpha=0.05
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("pettitt-u-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 <- "level"
ALPHA <- 0.05
d <- ordered(df, x_col, y_col)
v <- d[[y_col]]
n <- length(v)
u <- 2 * cumsum(rank(v))[1:(n - 1)] - seq_len(n - 1) * (n + 1) # as trend::pettitt.test
K <- max(abs(u))
loc <- which.max(abs(u))
pv <- min(1, 2 * exp(-6 * K^2 / (n^3 + n^2)))
crit <- sqrt(-log(ALPHA / 2) * (n^3 + n^2) / 6)
pu <- data.frame(t = time_of(d, x_col)[1:(n - 1)], u = u)
p <- ggplot(pu, aes(t, u)) + annotate("rect", xmin = -Inf, xmax = Inf, ymin = -crit, ymax = crit, fill = grey_col, alpha = 0.3) +
geom_hline(yintercept = c(-crit, crit), colour = ref_col, linetype = "dashed") + geom_line(colour = cs_cat[1]) +
geom_point(data = pu[loc, ], colour = "#ce5342", size = 2.5) +
labs(x = "month", y = "U_t", title = sprintf("Pettitt K = %.0f, p ≈ %.3g", K, pv)) + theme_cs
print(p)Needs ggplot2 · reads pettitt-u-demo.csv · app theme from the optional codesplashr helper