svgmediation-path
Mediation path diagram
How much of an exposure's effect runs through a mediator?
How to read it
- Read the top path: exposure → mediator (a), mediator → outcome (b).
- Read the bottom path: the direct effect (c′).
- Read the indirect effect (a×b) at the bottom with its interval.
- Callout 1: Path a: exposure to mediator.
- Callout 2: Path b: mediator to outcome.
- Callout 3: Direct effect.
- Callout 4: Indirect effect and total.
Watch out
- Calling this causal needs no unmeasured confounding on every path, which data alone cannot show.
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.
- Paths a and b are the mediator and outcome models' coefficients; ACME, ADE (c′) and total come from the engine's bootstrap or quasi-Bayesian simulation, so ACME need not equal a × b exactly with interactions or non-linear models.
- The diagram states a causal model: the indirect effect is causal only under sequential ignorability.
# Mediation path diagram — Codesplash Chart Lab (recipe "mediation-path")
# 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("mediation-path-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["path"] = pd.Categorical(df["path"].astype("string"), categories=["x", "m", "y", "a", "b", "c_prime", "acme", "total"])
_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")
PATH = "path"
EST = "estimate"
LO = "low"
HI = "high"
P = "p"
NAME = "name"
def norm(p):
p = str(p).lower().replace("′", "_prime").replace("'", "_prime").replace(" ", "_")
return {"c": "c_prime", "direct": "c_prime", "ade": "c_prime", "indirect": "acme"}.get(p, p)
key = df[PATH].map(norm)
names = {k: (str(df.loc[key == k, NAME].iloc[0]) if NAME and (key == k).any() else k.upper()) for k in ("x", "m", "y")}
def label(k):
r = df[key == k]
if r.empty or pd.isna(r[EST].iloc[0]):
return "—"
s = f"{r[EST].iloc[0]:.2f}"
if LO and HI and pd.notna(r[LO].iloc[0]):
s += f" [{r[LO].iloc[0]:.2f}, {r[HI].iloc[0]:.2f}]"
if P and pd.notna(r[P].iloc[0]):
p = r[P].iloc[0]
s += ", p < .001" if p < 0.001 else f", p = {p:.3f}".replace("0.", ".")
return s
pos = {"x": (0.12, 0.25), "m": (0.5, 0.82), "y": (0.88, 0.25)}
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.set_axis_off()
box = dict(boxstyle="round,pad=0.5", facecolor="none", edgecolor=plt.rcParams["text.color"])
for k, (x, y) in pos.items():
ax.text(x, y, names[k], ha="center", va="center", fontsize=11, fontweight="bold", bbox=box)
arrow = dict(arrowstyle="-|>", color=PALETTE[0], lw=1.6)
ax.annotate("", xy=(0.43, 0.75), xytext=(0.16, 0.32), arrowprops=arrow)
ax.annotate("", xy=(0.84, 0.32), xytext=(0.57, 0.75), arrowprops=arrow)
ax.annotate("", xy=(0.78, 0.25), xytext=(0.22, 0.25), arrowprops=dict(arrowstyle="-|>", color=REF, lw=1.4))
ax.text(0.27, 0.56, "a " + label("a"), ha="right", fontsize=9)
ax.text(0.73, 0.56, "b " + label("b"), ha="left", fontsize=9)
ax.text(0.5, 0.29, "c′ (direct) " + label("c_prime"), ha="center", fontsize=9)
ax.text(0.5, 0.08, "indirect (ACME) " + label("acme") + "\ntotal " + label("total"), ha="center", fontsize=9)
plt.show()Needs pandas, numpy, matplotlib · reads mediation-path-demo.csv · app theme from the optional codesplash helper
# Mediation path diagram — Codesplash Chart Lab (recipe "mediation-path")
# 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("mediation-path-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["path"] = pd.Categorical(df["path"].astype("string"), categories=["x", "m", "y", "a", "b", "c_prime", "acme", "total"])
_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")
PATH = "path"
EST = "estimate"
LO = "low"
HI = "high"
P = "p"
NAME = "name"
def norm(p):
p = str(p).lower().replace("′", "_prime").replace("'", "_prime").replace(" ", "_")
return {"c": "c_prime", "direct": "c_prime", "ade": "c_prime", "indirect": "acme"}.get(p, p)
key = df[PATH].map(norm)
names = {k: (str(df.loc[key == k, NAME].iloc[0]) if NAME and (key == k).any() else k.upper()) for k in ("x", "m", "y")}
def label(k):
r = df[key == k]
if r.empty or pd.isna(r[EST].iloc[0]):
return "—"
s = f"{r[EST].iloc[0]:.2f}"
if LO and HI and pd.notna(r[LO].iloc[0]):
s += f" [{r[LO].iloc[0]:.2f}, {r[HI].iloc[0]:.2f}]"
if P and pd.notna(r[P].iloc[0]):
p = r[P].iloc[0]
s += ", p < .001" if p < 0.001 else f", p = {p:.3f}".replace("0.", ".")
return s
pos = {"x": (0.12, 0.25), "m": (0.5, 0.82), "y": (0.88, 0.25)}
fig = go.Figure()
for k, (x, y) in pos.items():
fig.add_annotation(x=x, y=y, text=f"<b>{names[k]}</b>", showarrow=False, bordercolor=REF, borderpad=8, font=dict(size=13))
for (x0, y0), (x1, y1) in [((0.16, 0.32), (0.43, 0.75)), ((0.57, 0.75), (0.84, 0.32)), ((0.22, 0.25), (0.78, 0.25))]:
fig.add_annotation(x=x1, y=y1, ax=x0, ay=y0, xref="x", yref="y", axref="x", ayref="y", showarrow=True, arrowhead=2, arrowwidth=1.6, arrowcolor=PALETTE[0])
for x, y, t in [(0.27, 0.56, "a " + label("a")), (0.73, 0.56, "b " + label("b")), (0.5, 0.31, "c′ " + label("c_prime")), (0.5, 0.1, "indirect " + label("acme")), (0.5, 0.02, "total " + label("total"))]:
fig.add_annotation(x=x, y=y, text=t, showarrow=False, font=dict(size=11))
fig.update_xaxes(visible=False, range=[0, 1])
fig.update_yaxes(visible=False, range=[0, 1])
fig.show()Needs pandas, numpy, plotly · reads mediation-path-demo.csv · app theme from the optional codesplash helper
# Mediation path diagram — Codesplash Chart Lab (recipe "mediation-path")
# 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("mediation-path-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["path"]] <- factor(df[["path"]], levels = c("x", "m", "y", "a", "b", "c_prime", "acme", "total"))
df[["name"]] <- factor(df[["name"]])
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
path_col <- "path"
est_col <- "estimate"
lo_col <- "low"
hi_col <- "high"
p_col <- "p"
name_col <- "name"
norm <- function(p) { p <- gsub(" ", "_", gsub("[′']", "_prime", tolower(p))); m <- c(c = "c_prime", direct = "c_prime", ade = "c_prime", indirect = "acme"); ifelse(p %in% names(m), m[p], p) }
key <- norm(as.character(df[[path_col]]))
nm <- function(k) { i <- which(key == k)[1]; if (is.null(name_col) || is.na(i) || df[[name_col]][i] == "") toupper(k) else as.character(df[[name_col]][i]) }
lab <- function(k) {
i <- which(key == k)[1]; if (is.na(i) || is.na(df[[est_col]][i])) return("—")
s <- sprintf("%.2f", df[[est_col]][i])
if (!is.null(lo_col) && !is.na(df[[lo_col]][i])) s <- sprintf("%s [%.2f, %.2f]", s, df[[lo_col]][i], df[[hi_col]][i])
if (!is.null(p_col) && !is.na(df[[p_col]][i])) s <- paste0(s, ", ", if (df[[p_col]][i] < 0.001) "p < .001" else sub("0\\.", ".", sprintf("p = %.3f", df[[p_col]][i])))
s
}
nodes <- data.frame(x = c(0.12, 0.5, 0.88), y = c(0.25, 0.82, 0.25), lab = c(nm("x"), nm("m"), nm("y")))
edges <- data.frame(x = c(0.16, 0.57, 0.22), y = c(0.32, 0.75, 0.25), xend = c(0.43, 0.84, 0.78), yend = c(0.75, 0.32, 0.25))
p <- ggplot() + geom_segment(data = edges, aes(x, y, xend = xend, yend = yend), arrow = arrow(length = unit(0.12, "inches"), type = "closed"), colour = cs_cat[1]) +
geom_label(data = nodes, aes(x, y, label = lab), fontface = "bold", label.padding = unit(0.5, "lines")) +
annotate("text", x = 0.27, y = 0.56, label = paste("a", lab("a")), hjust = 1, size = 3.2) +
annotate("text", x = 0.73, y = 0.56, label = paste("b", lab("b")), hjust = 0, size = 3.2) +
annotate("text", x = 0.5, y = 0.3, label = paste("c′ (direct)", lab("c_prime")), size = 3.2) +
annotate("text", x = 0.5, y = 0.08, label = paste0("indirect (ACME) ", lab("acme"), "\ntotal ", lab("total")), size = 3.2) +
coord_cartesian(xlim = c(0, 1), ylim = c(0, 1)) + theme_void()
print(p)Needs ggplot2 · reads mediation-path-demo.csv · app theme from the optional codesplashr helper