svgmargin-plot
Non-inferiority & equivalence margins
Does the interval clear the margin — non-inferior, equivalent, inferior or inconclusive?
How to read it
- Read each interval against the shaded margin.
- Fully inside the margin: equivalent. Above the lower bound: non-inferior.
- Crossing a boundary: inconclusive.
- Callout 1: An interval inside the margin.
- Callout 2: An interval crossing the boundary: inconclusive.
- Callout 3: The verdict for each comparison.
Watch out
- The margin must be justified before the data are seen: moving it afterwards invalidates the conclusion.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing inferential.
- Differences are oriented so higher is better (treatment − control for a good outcome); a lower margin alone is a non-inferiority question, both margins an equivalence one.
- Verdicts follow Piaggio et al. (2012, CONSORT NI): interval above max(0, −Δ) superior; above −Δ non-inferior; below −Δ inferior; otherwise inconclusive. Equivalence needs the whole interval inside ±Δ.
- Margins must be fixed before the data are seen; the shaded band is the region of practical equivalence.
# Non-inferiority & equivalence margins — Codesplash Chart Lab (recipe "margin-plot")
# controls: defaults
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("margin-plot-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["comparison"] = pd.Categorical(df["comparison"].astype("string"), categories=["Site A", "Site B", "Site C", "Pooled"])
_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 first(col):
"""The first finite value of a column the engine repeats on every row (None if absent)."""
if col is None:
return None
v = pd.to_numeric(df[col], errors="coerce").dropna()
return float(v.iloc[0]) if len(v) else None
LABEL = "comparison"
EST = "difference"
LO = "low"
HI = "high"
NOTE = None
FIT = None
LOG = False
d = df.dropna(subset=[EST]).drop_duplicates(subset=[LABEL]).reset_index(drop=True)
pos = np.arange(len(d))[::-1] # first row at the top
fig, ax = plt.subplots(figsize=(8, 0.45 * len(d) + 1.4))
MLV = "margin"
MHV = None
ML, MH = first(MLV), first(MHV)
def verdict(lo, hi): # Piaggio et al. (2012): CI against the margin(s)
if ML is not None and MH is not None:
return "equivalent" if lo > ML and hi < MH else ("not equivalent" if hi < ML or lo > MH else "inconclusive")
m = ML if ML is not None else MH
if m is None: return "inconclusive"
return "superior" if lo > max(0, m) else "non-inferior" if lo > m else "inferior" if hi < m else "inconclusive"
d["_note"] = [verdict(lo, hi) for lo, hi in zip(d[LO], d[HI])]
d["_color"] = d["_note"].map({"inferior": "#c13e2e", "not equivalent": "#c13e2e", "inconclusive": "#c27c0e"}).fillna("#19966e")
zone = (ML, MH) if ML is not None and MH is not None else ((ML, float(d[HI].max())) if ML is not None else None)
if zone is not None:
ax.axvspan(*zone, color="#19966e", alpha=0.1, lw=0)
ax.axvline(0, color=REF, linestyle="--", linewidth=1)
if FIT and d[FIT].notna().all():
ax.plot(pos, d[FIT], color=PALETTE[1], linestyle="--", linewidth=1.8, label="fitted")
colors = d["_color"] if "_color" in d else [PALETTE[0]] * len(d)
for i, row in d.iterrows():
lo, hi = (row[LO], row[HI]) if LO and HI else (np.nan, np.nan)
ax.errorbar(row[EST], pos[i], xerr=[[row[EST] - lo], [hi - row[EST]]] if np.isfinite(lo) else None, fmt="o", color=colors[i], capsize=3)
note = row.get("_note") if "_note" in d else (row[NOTE] if NOTE and pd.notna(row.get(NOTE)) else None)
if note is not None and note == note:
txt = note if isinstance(note, str) else ("p < .001" if note < 0.001 else f"p = {note:.3f}".replace("0.", "."))
ax.annotate(txt, (1.01, pos[i]), xycoords=("axes fraction", "data"), va="center", fontsize=8, color=REF)
ax.set_yticks(pos, d[LABEL].astype(str))
ax.set_xlabel("difference (higher is better)")
if LOG:
ax.set_xscale("log")
plt.show()Needs pandas, numpy, matplotlib · reads margin-plot-demo.csv · app theme from the optional codesplash helper
# Non-inferiority & equivalence margins — Codesplash Chart Lab (recipe "margin-plot")
# controls: defaults
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("margin-plot-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["comparison"] = pd.Categorical(df["comparison"].astype("string"), categories=["Site A", "Site B", "Site C", "Pooled"])
_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 first(col):
"""The first finite value of a column the engine repeats on every row (None if absent)."""
if col is None:
return None
v = pd.to_numeric(df[col], errors="coerce").dropna()
return float(v.iloc[0]) if len(v) else None
LABEL = "comparison"
EST = "difference"
LO = "low"
HI = "high"
NOTE = None
FIT = None
d = df.dropna(subset=[EST]).drop_duplicates(subset=[LABEL]).reset_index(drop=True)
labels = d[LABEL].astype(str)
MLV = "margin"
MHV = None
ML, MH = first(MLV), first(MHV)
def verdict(lo, hi): # Piaggio et al. (2012): CI against the margin(s)
if ML is not None and MH is not None:
return "equivalent" if lo > ML and hi < MH else ("not equivalent" if hi < ML or lo > MH else "inconclusive")
m = ML if ML is not None else MH
if m is None: return "inconclusive"
return "superior" if lo > max(0, m) else "non-inferior" if lo > m else "inferior" if hi < m else "inconclusive"
d["_note"] = [verdict(lo, hi) for lo, hi in zip(d[LO], d[HI])]
d["_color"] = d["_note"].map({"inferior": "#c13e2e", "not equivalent": "#c13e2e", "inconclusive": "#c27c0e"}).fillna("#19966e")
zone = (ML, MH) if ML is not None and MH is not None else ((ML, float(d[HI].max())) if ML is not None else None)
err = dict(type="data", symmetric=False, array=d[HI] - d[EST], arrayminus=d[EST] - d[LO]) if LO and HI else None
notes = d["_note"] if "_note" in d else (d[NOTE].map(lambda p: "" if pd.isna(p) else ("p < .001" if p < 0.001 else f"p = {p:.3f}".replace("0.", "."))) if NOTE else None)
fig = go.Figure()
fig.add_scatter(x=d[EST], y=labels, mode="markers+text" if notes is not None else "markers", text=notes, textposition="middle right", error_x=err, marker=dict(size=9, color=list(d["_color"]) if "_color" in d else PALETTE[0]), showlegend=False)
if FIT and d[FIT].notna().all():
fig.add_scatter(x=labels, y=d[FIT], mode="lines", line=dict(color=PALETTE[1], dash="dash"), name="fitted")
fig.add_vline(x=0, line_dash="dash", line_color=REF)
if zone is not None:
fig.add_vrect(x0=zone[0], x1=zone[1], fillcolor="#19966e", opacity=0.1, line_width=0)
fig.update_yaxes(categoryorder="array", categoryarray=list(labels)[::-1])
fig.update_xaxes(title="difference (higher is better)")
fig.show()Needs pandas, numpy, plotly · reads margin-plot-demo.csv · app theme from the optional codesplash helper
# Non-inferiority & equivalence margins — Codesplash Chart Lab (recipe "margin-plot")
# controls: defaults
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("margin-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["comparison"]] <- factor(df[["comparison"]], levels = c("Site A", "Site B", "Site C", "Pooled"))
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
first_num <- function(col) { if (is.null(col)) return(NA_real_); v <- suppressWarnings(as.numeric(df[[col]])); v <- v[is.finite(v)]; if (length(v)) v[1] else NA_real_ }
label_col <- "comparison"
est_col <- "difference"
lo_col <- "low"
hi_col <- "high"
note_col <- NULL
fit_col <- NULL
d <- df[!is.na(df[[est_col]]), ]
d <- d[!duplicated(as.character(d[[label_col]])), ]
d <- data.frame(lab = factor(as.character(d[[label_col]]), levels = rev(unique(as.character(d[[label_col]])))), est = d[[est_col]],
lo = if (is.null(lo_col)) NA_real_ else d[[lo_col]], hi = if (is.null(hi_col)) NA_real_ else d[[hi_col]],
note = if (is.null(note_col)) NA_real_ else suppressWarnings(as.numeric(d[[note_col]])), fit = if (is.null(fit_col)) NA_real_ else d[[fit_col]])
d$note_txt <- ifelse(is.na(d$note), "", ifelse(d$note < 0.001, "p < .001", sub("^0", "", sprintf("p = %.3f", d$note))))
ml_col <- "margin"
mh_col <- NULL
ml <- first_num(ml_col); mh <- first_num(mh_col)
verdict <- function(lo, hi) { # Piaggio et al. (2012)
if (!is.na(ml) && !is.na(mh)) return(if (lo > ml && hi < mh) "equivalent" else if (hi < ml || lo > mh) "not equivalent" else "inconclusive")
m <- if (!is.na(ml)) ml else mh
if (is.na(m)) "inconclusive" else if (lo > max(0, m)) "superior" else if (lo > m) "non-inferior" else if (hi < m) "inferior" else "inconclusive"
}
d$note_txt <- mapply(verdict, d$lo, d$hi)
zone <- if (!is.na(ml) && !is.na(mh)) c(ml, mh) else if (!is.na(ml)) c(ml, max(d$hi, na.rm = TRUE)) else NULL
p <- ggplot(d, aes(est, lab)) +
{ if (!is.null(zone)) annotate("rect", xmin = zone[1], xmax = zone[2], ymin = -Inf, ymax = Inf, fill = "#19966e", alpha = 0.1) } +
geom_vline(xintercept = 0, linetype = "dashed", colour = ref_col) +
{ if (all(!is.na(d$fit))) geom_line(aes(x = fit, group = 1), colour = cs_cat[2], linetype = "dashed", linewidth = 0.9) } +
geom_errorbar(aes(xmin = lo, xmax = hi), width = 0.15, orientation = "y", colour = cs_cat[1], na.rm = TRUE) +
geom_point(size = 2.6, colour = cs_cat[1]) +
geom_text(aes(label = note_txt), hjust = -0.25, vjust = -0.8, size = 3, colour = ref_col) +
labs(x = "difference (higher is better)", y = NULL) + theme_cs
print(p)Needs ggplot2 · reads margin-plot-demo.csv · app theme from the optional codesplashr helper