Skip to content
svgmann-kendall-sen

Trend with Sen's slope

Is the series drifting up or down, and by how much per period?

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

How to read it

  1. Read the bold line as Sen's slope: the median change per period.
  2. Read the dashed lines as its interval.
  3. Read the title for Mann–Kendall's τ and p.
  1. Callout 1: Sen's slope: the rate of change.
  2. Callout 2: Dashed lines: the slope's interval.
  3. Callout 3: The rate per observation.

Watch out

  • Autocorrelation inflates the plain test. Use the corrected variants when the series has memory.

Defaults

Interval level
0.95
How often intervals built this way contain the true value, over repeated samples.
Range 0.5 to 0.999, step 0.01

Pinned in the code

  • Slope = median of (x_j − x_i)/(t_j − t_i) over all pairs; t is the position for dates or row order, the value for a numeric time.
  • Interval: Gilbert (1987) — ranks (N ∓ z√Var(S))/2 of the sorted pairwise slopes (rounded half to even, as trend::sens.slope).
  • Intercept: median of x − slope·t. Mann–Kendall z is continuity-corrected; Var(S) carries the tie correction.
  • Dashed lines share the median point and use the interval's slopes, showing how steep the trend could plausibly be.
# Trend with Sen's slope — Codesplash Chart Lab (recipe "mann-kendall-sen")
# controls: confLevel=0.95
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("mann-kendall-sen-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)
def sen_fit(t, v, conf=0.95):
    """Sen's slope (median pairwise slope), Gilbert's interval (R round = half to even) and Mann–Kendall."""
    i, j = np.triu_indices(len(v), 1)
    dt = t[j] - t[i]
    d = np.sort(((v[j] - v[i]) / dt)[dt != 0])
    m = len(d)
    s = float(np.sign(v[j] - v[i]).sum())
    _, ties = np.unique(v, return_counts=True)
    n = len(v)
    var = (n * (n - 1) * (2 * n + 5) - (ties * (ties - 1) * (2 * ties + 5)).sum()) / 18
    c = stats.norm.ppf(1 - (1 - conf) / 2) * np.sqrt(var)
    lo, hi = int(round((m - c) / 2)), int(round((m + c) / 2 + 1))
    slope = float(np.median(d))
    z = 0.0 if s == 0 else (s - np.sign(s)) / np.sqrt(var)
    return dict(slope=slope, low=d[lo - 1] if 1 <= lo <= m else np.nan, high=d[hi - 1] if 1 <= hi <= m else np.nan,
                intercept=float(np.median(v - slope * t)), tau=s / (n * (n - 1) / 2), p=2 * stats.norm.sf(abs(z)))
X = "month"
Y = "index"
FIT = None
CONF = 0.95
d = ordered(df, X, [Y, FIT])
v = d[Y].to_numpy(dtype=float)
numeric_time = X is not None and not pd.api.types.is_datetime64_any_dtype(d[X])
tpos = d[X].to_numpy(dtype=float) if numeric_time else np.arange(1.0, len(v) + 1)  # dates → position in time order
f = sen_fit(tpos, v, CONF)
t = time_of(d, X)
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(t, v, color=PALETTE[0], alpha=0.35, linewidth=1)
ax.scatter(t, v, color=PALETTE[0], s=10)
if FIT:
    ax.plot(t, d[FIT], color="black", linewidth=2, label="trend")
else:
    tm = np.sort(tpos)[(len(tpos) - 1) // 2]
    mid = f["intercept"] + f["slope"] * tm
    for s_ in (f["low"], f["high"]):  # the interval's slopes through the median point
        ax.plot(t, mid + s_ * (tpos - tm), color=REF, linestyle="--", linewidth=1)
    ax.plot(t, f["intercept"] + f["slope"] * tpos, color="black", linewidth=2, label=f"Sen's slope {f['slope']:.4g}")
ax.set_title(f"Mann–Kendall τ = {f['tau']:.2f}, p = {f['p']:.3g}", fontsize=10, loc="left")
ax.set_xlabel("month")
ax.set_ylabel(Y)
ax.legend(frameon=False)
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads mann-kendall-sen-demo.csv · app theme from the optional codesplash helper