svgmann-kendall-sen
Trend with Sen's slope
Is the series drifting up or down, and by how much per period?
How to read it
- Read the bold line as Sen's slope: the median change per period.
- Read the dashed lines as its interval.
- Read the title for Mann–Kendall's τ and p.
- Callout 1: Sen's slope: the rate of change.
- Callout 2: Dashed lines: the slope's interval.
- 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
# 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 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("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)
f = sen_fit(tpos, v, CONF)
t = time_of(d, X)
fig = go.Figure(go.Scatter(x=t, y=v, mode="lines+markers", line=dict(color=PALETTE[0], width=1), marker=dict(size=5), name=Y))
if FIT:
fig.add_scatter(x=t, y=d[FIT], mode="lines", line=dict(color="black", width=2), name="trend")
else:
tm = np.sort(tpos)[(len(tpos) - 1) // 2]
mid = f["intercept"] + f["slope"] * tm
for s_ in (f["low"], f["high"]):
fig.add_scatter(x=t, y=mid + s_ * (tpos - tm), mode="lines", line=dict(color=REF, dash="dash", width=1), showlegend=False)
fig.add_scatter(x=t, y=f["intercept"] + f["slope"] * tpos, mode="lines", line=dict(color="black", width=2), name=f"Sen's slope {f['slope']:.4g}")
fig.update_layout(title=f"Mann–Kendall τ = {f['tau']:.2f}, p = {f['p']:.3g}", xaxis_title="month", yaxis_title=Y)
fig.show()Needs pandas, numpy, plotly, scipy · reads mann-kendall-sen-demo.csv · app theme from the optional codesplash helper
# Trend with Sen's slope — Codesplash Chart Lab (recipe "mann-kendall-sen")
# controls: confLevel=0.95
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("mann-kendall-sen-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]]
sen_fit <- function(t, v, conf = 0.95) {
# Sen's slope (median pairwise slope), Gilbert's interval and Mann–Kendall (as trend::sens.slope / mk.test)
ij <- which(upper.tri(matrix(0, length(v), length(v))), arr.ind = TRUE)
dt <- t[ij[, 2]] - t[ij[, 1]]
d <- sort(((v[ij[, 2]] - v[ij[, 1]]) / dt)[dt != 0])
m <- length(d)
s <- sum(sign(v[ij[, 2]] - v[ij[, 1]]))
n <- length(v)
ties <- as.numeric(table(v))
var <- (n * (n - 1) * (2 * n + 5) - sum(ties * (ties - 1) * (2 * ties + 5))) / 18
c <- stats::qnorm(1 - (1 - conf) / 2) * sqrt(var)
lo <- round((m - c) / 2)
hi <- round((m + c) / 2 + 1)
slope <- stats::median(d)
z <- if (s == 0) 0 else (s - sign(s)) / sqrt(var)
list(slope = slope, low = if (lo >= 1 && lo <= m) d[lo] else NA, high = if (hi >= 1 && hi <= m) d[hi] else NA,
intercept = stats::median(v - slope * t), tau = s / (n * (n - 1) / 2), p = 2 * stats::pnorm(-abs(z)))
}
x_col <- "month"
y_col <- "index"
fit_col <- NULL
CONF <- 0.95
d <- ordered(df, x_col, c(y_col, fit_col))
v <- d[[y_col]]
numeric_time <- !is.null(x_col) && is.numeric(d[[x_col]])
tpos <- if (numeric_time) d[[x_col]] else seq_along(v) # dates → position in time order
f <- sen_fit(tpos, v, CONF)
d$t <- time_of(d, x_col)
tm <- sort(tpos)[(length(tpos) - 1) %/% 2 + 1]
mid <- f$intercept + f$slope * tm
d$line <- if (!is.null(fit_col)) d[[fit_col]] else f$intercept + f$slope * tpos
d$lo <- mid + f$low * (tpos - tm)
d$hi <- mid + f$high * (tpos - tm)
p <- ggplot(d, aes(t, .data[[y_col]])) + geom_line(colour = cs_cat[1], alpha = 0.35) + geom_point(colour = cs_cat[1], size = 1) +
{ if (is.null(fit_col)) list(geom_line(aes(y = lo), colour = ref_col, linetype = "dashed"), geom_line(aes(y = hi), colour = ref_col, linetype = "dashed")) } +
geom_line(aes(y = line), linewidth = 1) +
labs(x = "month", y = y_col, title = sprintf("Mann–Kendall τ = %.2f, p = %.3g; Sen's slope %.4g", f$tau, f$p, f$slope)) + theme_cs
print(p)Needs ggplot2 · reads mann-kendall-sen-demo.csv · app theme from the optional codesplashr helper