svgbrushableoutlier-consensus
Outlier consensus
Which values look unusual, and do the common outlier rules agree?
How to read it
- Read rows as how many of the three rules flag a value: the top row is flagged by all three.
- Read the vertical lines as each rule's cutoff.
- Investigate values flagged by all three first.
- Callout 1: Flagged by all three rules: look at these first.
- Callout 2: Bottom row: not flagged by any rule.
- Callout 3: Each dashed line: one rule's cutoff.
Watch out
- Being flagged doesn't make a value wrong: check the source before removing it.
Defaults
- Log x axis (positive values)
- Off
- Display only; the rules use the raw values.
Pinned in the code
- Tukey: outside [Q1 − 1.5·IQR, Q3 + 1.5·IQR] with type-7 quartiles.
- z: |x − x̄| / s > 3 with s on n − 1; not applied when n ≤ 10 (max |z| ≤ (n − 1)/√n).
- Modified z (Iglewicz & Hoaglin): |x − median| / (1.4826·MAD) > 3.5; when MAD = 0 the scale is 1.253314·mean absolute deviation.
- Consensus = number of rules flagging a value (0–3). Flags are screening hints, never automatic deletions.
# Outlier consensus — Codesplash Chart Lab (recipe "outlier-consensus")
# controls: log=false
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("outlier-consensus-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_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")
v = df["response_ms"].dropna().to_numpy(dtype=float)
q1, q3 = np.percentile(v, [25, 75]) # type-7 quartiles (numpy's default "linear")
iqr = q3 - q1
tukey = (v < q1 - 1.5 * iqr) | (v > q3 + 1.5 * iqr)
m, s = v.mean(), v.std(ddof=1)
z = (np.abs(v - m) > 3 * s) if len(v) > 10 and s > 0 else np.zeros(len(v), bool) # not applied when n ≤ 10
med = np.median(v)
mad = np.median(np.abs(v - med))
scale = 1.4826 * mad if mad > 0 else 1.253314 * np.mean(np.abs(v - med)) # Iglewicz & Hoaglin; meanAD when MAD = 0
modz = (np.abs(v - med) > 3.5 * scale) if scale > 0 else np.zeros(len(v), bool)
votes = tukey.astype(int) + z + modz # consensus 0–3: screening hints, never automatic deletions
rng = np.random.default_rng(11) # deterministic jitter within each band
y = votes + rng.uniform(-0.3, 0.3, len(v))
fig, ax = plt.subplots(figsize=(8, 3.6))
for k, colour in zip(range(4), [GREY, PALETTE[1], PALETTE[3], DIV[0]]):
m_k = votes == k
ax.scatter(v[m_k], y[m_k], s=12, color=colour, alpha=0.8, edgecolors="none")
for lo, hi, colour, ls, label in [(q1 - 1.5 * iqr, q3 + 1.5 * iqr, REF, "-", "Tukey 1.5×IQR"), (m - 3 * s, m + 3 * s, PALETTE[0], "--", "|z| = 3"), (med - 3.5 * scale, med + 3.5 * scale, PALETTE[2], ":", "|mod z| = 3.5")]:
ax.axvline(lo, color=colour, linestyle=ls, linewidth=1.3, label=label)
ax.axvline(hi, color=colour, linestyle=ls, linewidth=1.3)
ax.set_yticks(range(4), [f"{k} rule{'s' if k != 1 else ''} · {(votes == k).sum()}" for k in range(4)])
ax.set_xlabel("response_ms")
ax.legend(fontsize=8, loc="upper right")
plt.show()Needs pandas, numpy, matplotlib · reads outlier-consensus-demo.csv · app theme from the optional codesplash helper
# Outlier consensus — Codesplash Chart Lab (recipe "outlier-consensus")
# controls: log=false
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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("outlier-consensus-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_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")
v = df["response_ms"].dropna().to_numpy(dtype=float)
q1, q3 = np.percentile(v, [25, 75]) # type-7 quartiles (numpy's default "linear")
iqr = q3 - q1
tukey = (v < q1 - 1.5 * iqr) | (v > q3 + 1.5 * iqr)
m, s = v.mean(), v.std(ddof=1)
z = (np.abs(v - m) > 3 * s) if len(v) > 10 and s > 0 else np.zeros(len(v), bool) # not applied when n ≤ 10
med = np.median(v)
mad = np.median(np.abs(v - med))
scale = 1.4826 * mad if mad > 0 else 1.253314 * np.mean(np.abs(v - med)) # Iglewicz & Hoaglin; meanAD when MAD = 0
modz = (np.abs(v - med) > 3.5 * scale) if scale > 0 else np.zeros(len(v), bool)
votes = tukey.astype(int) + z + modz # consensus 0–3: screening hints, never automatic deletions
y = votes + np.random.default_rng(11).uniform(-0.3, 0.3, len(v))
fig = go.Figure(go.Scatter(x=v, y=y, mode="markers", marker=dict(size=6, color=votes, colorscale=[[0, GREY], [0.34, PALETTE[1]], [0.67, PALETTE[3]], [1, DIV[0]]], cmin=0, cmax=3), text=[f"{k} rules" for k in votes]))
for lo, hi, colour, dash in [(q1 - 1.5 * iqr, q3 + 1.5 * iqr, REF, "solid"), (m - 3 * s, m + 3 * s, PALETTE[0], "dash"), (med - 3.5 * scale, med + 3.5 * scale, PALETTE[2], "dot")]:
for xv in (lo, hi):
fig.add_vline(x=xv, line=dict(color=colour, dash=dash, width=1.3))
fig.update_layout(yaxis=dict(tickvals=[0, 1, 2, 3], ticktext=["0 rules", "1 rule", "2 rules", "3 rules"]), xaxis_title="response_ms")
fig.show()Needs pandas, numpy, plotly · reads outlier-consensus-demo.csv · app theme from the optional codesplash helper
# Outlier consensus — Codesplash Chart Lab (recipe "outlier-consensus")
# controls: log=false
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("outlier-consensus-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
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
v <- df[["response_ms"]][!is.na(df[["response_ms"]])]
q <- stats::quantile(v, c(0.25, 0.75), type = 7); iqr <- q[[2]] - q[[1]]
tukey <- v < q[[1]] - 1.5 * iqr | v > q[[2]] + 1.5 * iqr
m <- mean(v); s <- stats::sd(v)
z <- if (length(v) > 10 && s > 0) abs(v - m) > 3 * s else rep(FALSE, length(v)) # not applied when n <= 10
med <- stats::median(v); mad_raw <- stats::mad(v, constant = 1)
scale <- if (mad_raw > 0) 1.4826 * mad_raw else 1.253314 * mean(abs(v - med)) # meanAD when MAD = 0
modz <- if (scale > 0) abs(v - med) > 3.5 * scale else rep(FALSE, length(v))
votes <- tukey + z + modz # consensus 0-3: screening hints, never automatic deletions
set.seed(11) # deterministic jitter within each band
pts <- data.frame(v = v, votes = votes, y = votes + stats::runif(length(v), -0.3, 0.3))
fences <- data.frame(x = c(q[[1]] - 1.5 * iqr, q[[2]] + 1.5 * iqr, m - 3 * s, m + 3 * s, med - 3.5 * scale, med + 3.5 * scale),
rule = rep(c("Tukey 1.5×IQR", "|z| = 3", "|mod z| = 3.5"), each = 2))
p <- ggplot(pts, aes(v, y)) +
geom_vline(data = fences, aes(xintercept = x, linetype = rule, colour = rule)) +
geom_point(aes(fill = factor(votes)), shape = 21, colour = "transparent", size = 1.8, alpha = 0.85) +
scale_fill_manual(values = c(`0` = grey_col, `1` = cs_cat[2], `2` = cs_cat[4], `3` = div_ramp[1]), guide = "none") +
scale_colour_manual(values = c("Tukey 1.5×IQR" = ref_col, "|z| = 3" = cs_cat[1], "|mod z| = 3.5" = cs_cat[3]), name = NULL) +
scale_linetype_manual(values = c("Tukey 1.5×IQR" = "solid", "|z| = 3" = "dashed", "|mod z| = 3.5" = "dotted"), name = NULL) +
scale_y_continuous(breaks = 0:3, labels = sprintf("%d rules · %d", 0:3, tabulate(votes + 1, 4))) +
labs(x = "response_ms", y = NULL) +
theme_cs
print(p)Needs ggplot2 · reads outlier-consensus-demo.csv · app theme from the optional codesplashr helper
-- Outlier consensus — Codesplash Chart Lab (recipe "outlier-consensus")
-- controls: log=false
-- per value: Tukey (type-7 quartiles), z (n > 10, SD on n − 1) and modified-z flags and their consensus
WITH v AS (SELECT "response_ms"::DOUBLE AS x FROM read_csv('outlier-consensus-demo.csv') WHERE "response_ms" IS NOT NULL),
s AS (
SELECT quantile_cont(x, 0.25) AS q1, quantile_cont(x, 0.75) AS q3, avg(x) AS m, stddev_samp(x) AS sd,
median(x) AS med, count(*) AS n
FROM v
),
d AS (SELECT median(abs(x - med)) AS mad, avg(abs(x - med)) AS mean_ad FROM v, s),
r AS (SELECT *, CASE WHEN mad > 0 THEN 1.4826 * mad ELSE 1.253314 * mean_ad END AS scale FROM s, d)
SELECT x,
(x < q1 - 1.5 * (q3 - q1) OR x > q3 + 1.5 * (q3 - q1)) AS tukey,
coalesce(n > 10 AND sd > 0 AND abs(x - m) > 3 * sd, false) AS z,
coalesce(scale > 0 AND abs(x - med) > 3.5 * scale, false) AS modified_z,
tukey::INTEGER + z::INTEGER + modified_z::INTEGER AS votes
FROM v, r
ORDER BY votes DESC, x;Needs duckdb · reads outlier-consensus-demo.csv