Skip to content
svgmediation-path

Mediation path diagram

How much of an exposure's effect runs through a mediator?

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

How to read it

  1. Read the top path: exposure → mediator (a), mediator → outcome (b).
  2. Read the bottom path: the direct effect (c′).
  3. Read the indirect effect (a×b) at the bottom with its interval.
  1. Callout 1: Path a: exposure to mediator.
  2. Callout 2: Path b: mediator to outcome.
  3. Callout 3: Direct effect.
  4. 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