svgforest-meta
Meta-analysis forest plot
How do the studies' effects compare, and what is the pooled effect and its spread?
How to read it
- Read each row as a study: square for estimate (larger means more weight), line for interval.
- Read the diamond at the bottom as the pooled estimate.
- Compare the rows' scatter with their intervals: more scatter than expected means heterogeneity.
- Callout 1: One study: square and interval.
- Callout 2: The diamond: the pooled estimate.
- Callout 3: Reference line: no effect.
Watch out
- A pooled number can hide real differences between studies. Read the prediction interval too.
Defaults
- Reference (null) value
- 0
- Where 'no effect' sits: 0 for differences, 1 for ratios.
- Range -1,000 to 1,000, step 0.1
- Log scale (ratios)
- Off
- Ratios on a log axis so equal ratios look equally far from 1.
Pinned in the code
- Draws the meta-analysis engine's numbers as given (codesplash.stats.meta in Python ≡ codesplashr in R); the chart computes nothing statistical.
- Studies keep the engine's order; the pooled row (kind = summary) is drawn as a diamond spanning its confidence interval.
- Marker area ∝ the study's weight in the pooled estimate (inverse variance, including τ² for random effects).
- The dashed line through the diamond is the prediction interval (engine controls piLow/piHigh): where a new study's true effect is expected.
- Ratios are back-transformed from the log scale and drawn on a log axis with the reference at 1.
# Meta-analysis forest plot — Codesplash Chart Lab (recipe "forest-meta")
# controls: reference=0, 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("forest-meta-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["study"] = pd.Categorical(df["study"].astype("string"), categories=["Aronson 1948", "Ferguson 1949", "Rosenthal 1960", "Hart 1977", "Frimodt 1973", "Stein 1953", "Vandiviere 1973", "Madras 1980", "Coetzee 1968", "Rosenthal 1961", "Pooled (RE)"])
df["row"] = pd.Categorical(df["row"].astype("string"), categories=["study", "summary"])
_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 fmt(v):
"""Number on a forest row, as in the app."""
if v is None or not np.isfinite(v):
return "—"
return f"{v:.0f}" if abs(v) >= 100 else f"{v:.1f}" if abs(v) >= 10 else f"{v:.2f}"
LABEL = "study"
EST = "risk ratio"
LOW = "low"
HIGH = "high"
WEIGHT = "weight %"
KIND = "row"
LOG, REFERENCE = False, 0 # the "no effect" value: 0 for differences, 1 for ratios
d = df.dropna(subset=[EST]).reset_index(drop=True)
y = np.arange(len(d))[::-1] # first row at the top
summary = d[KIND].astype(str).eq("summary") if KIND else pd.Series(False, index=d.index)
w = pd.to_numeric(d[WEIGHT], errors="coerce") if WEIGHT else pd.Series(np.nan, index=d.index)
PI_LOW, PI_HIGH = None, None # the prediction interval, when the result has one
w_max = w[~summary].max()
fig, ax = plt.subplots(figsize=(8.5, max(3, 0.34 * len(d) + 1.2)))
ax.axvline(REFERENCE, color=REF, linestyle="--", linewidth=1)
for i, row in d.iterrows():
yi = y[i]
note = f"{fmt(row[EST])} [{fmt(row[LOW])}, {fmt(row[HIGH])}]"
if summary[i]:
if PI_LOW is not None:
ax.plot([PI_LOW, PI_HIGH], [yi, yi], color=REF, linestyle=":", linewidth=1.4)
ax.fill([row[LOW], row[EST], row[HIGH], row[EST]], [yi, yi + 0.32, yi, yi - 0.32], color=plt.rcParams["text.color"], zorder=3)
else:
ax.plot([row[LOW], row[HIGH]], [yi, yi], color=PALETTE[0], linewidth=1.4)
size = 4 + 10 * np.sqrt(max(0, w[i]) / w_max) if np.isfinite(w[i]) and w_max > 0 else 7
ax.plot(row[EST], yi, marker="s", markersize=size, color=PALETTE[0], linestyle="none", zorder=3)
if np.isfinite(w[i]):
note += f" {w[i]:.1f}%"
ax.text(1.01, yi, note, transform=ax.get_yaxis_transform(), va="center", fontsize=8, fontweight="bold" if summary[i] else "normal")
if LOG:
ax.set_xscale("log")
ax.set_yticks(y, d[LABEL].astype(str))
ax.set_ylim(-0.7, len(d) - 0.3)
ax.set_xlabel(EST)
fig.tight_layout()
fig.subplots_adjust(right=0.74)
plt.show()Needs pandas, numpy, matplotlib · reads forest-meta-demo.csv · app theme from the optional codesplash helper
# Meta-analysis forest plot — Codesplash Chart Lab (recipe "forest-meta")
# controls: reference=0, 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("forest-meta-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["study"] = pd.Categorical(df["study"].astype("string"), categories=["Aronson 1948", "Ferguson 1949", "Rosenthal 1960", "Hart 1977", "Frimodt 1973", "Stein 1953", "Vandiviere 1973", "Madras 1980", "Coetzee 1968", "Rosenthal 1961", "Pooled (RE)"])
df["row"] = pd.Categorical(df["row"].astype("string"), categories=["study", "summary"])
_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 fmt(v):
"""Number on a forest row, as in the app."""
if v is None or not np.isfinite(v):
return "—"
return f"{v:.0f}" if abs(v) >= 100 else f"{v:.1f}" if abs(v) >= 10 else f"{v:.2f}"
LABEL = "study"
EST = "risk ratio"
LOW = "low"
HIGH = "high"
WEIGHT = "weight %"
KIND = "row"
LOG, REFERENCE = False, 0 # the "no effect" value: 0 for differences, 1 for ratios
d = df.dropna(subset=[EST]).reset_index(drop=True)
y = np.arange(len(d))[::-1] # first row at the top
summary = d[KIND].astype(str).eq("summary") if KIND else pd.Series(False, index=d.index)
w = pd.to_numeric(d[WEIGHT], errors="coerce") if WEIGHT else pd.Series(np.nan, index=d.index)
PI_LOW, PI_HIGH = None, None # the prediction interval, when the result has one
w_max = w[~summary].max()
st = d[~summary]
fig = go.Figure()
fig.add_vline(x=REFERENCE, line=dict(color=REF, dash="dash", width=1))
for i, row in st.iterrows():
fig.add_scatter(x=[row[LOW], row[HIGH]], y=[y[i], y[i]], mode="lines", line=dict(color=PALETTE[0], width=1.4), showlegend=False, hoverinfo="skip")
sizes = [4 + 10 * np.sqrt(max(0, w[i]) / w_max) if np.isfinite(w[i]) and w_max > 0 else 7 for i in st.index]
fig.add_scatter(x=st[EST], y=y[st.index], mode="markers", marker=dict(symbol="square", size=sizes, color=PALETTE[0]), name="study", text=st[LABEL].astype(str))
for i, row in d[summary].iterrows():
if PI_LOW is not None:
fig.add_scatter(x=[PI_LOW, PI_HIGH], y=[y[i], y[i]], mode="lines", line=dict(color=REF, dash="dot", width=1.4), name="prediction interval")
fig.add_scatter(x=[row[LOW], row[EST], row[HIGH], row[EST], row[LOW]], y=[y[i], y[i] + 0.32, y[i], y[i] - 0.32, y[i]], mode="lines", fill="toself",
line=dict(color=REF), fillcolor=REF, name="pooled estimate")
labels = [f"{r[LABEL]} {fmt(r[EST])} [{fmt(r[LOW])}, {fmt(r[HIGH])}]" for _, r in d.iterrows()]
fig.update_yaxes(tickmode="array", tickvals=list(y), ticktext=labels, range=[-0.7, len(d) - 0.3])
fig.update_xaxes(type="log" if LOG else "linear", title=EST)
fig.update_layout(showlegend=False)
fig.show()Needs pandas, numpy, plotly · reads forest-meta-demo.csv · app theme from the optional codesplash helper
# Meta-analysis forest plot — Codesplash Chart Lab (recipe "forest-meta")
# controls: reference=0, 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("forest-meta-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["study"]] <- factor(df[["study"]], levels = c("Aronson 1948", "Ferguson 1949", "Rosenthal 1960", "Hart 1977", "Frimodt 1973", "Stein 1953", "Vandiviere 1973", "Madras 1980", "Coetzee 1968", "Rosenthal 1961", "Pooled (RE)"))
df[["row"]] <- factor(df[["row"]], levels = c("study", "summary"))
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
fmt <- function(v) {
ifelse(!is.finite(v), "—", ifelse(abs(v) >= 100, sprintf("%.0f", v), ifelse(abs(v) >= 10, sprintf("%.1f", v), sprintf("%.2f", v))))
}
label_col <- "study"
est_col <- "risk ratio"
low_col <- "low"
high_col <- "high"
weight_col <- "weight %"
kind_col <- "row"
use_log <- FALSE; reference <- 0 # the "no effect" value: 0 for differences, 1 for ratios
keep <- !is.na(df[[est_col]])
d <- data.frame(label = as.character(df[[label_col]][keep]), est = df[[est_col]][keep], low = df[[low_col]][keep], high = df[[high_col]][keep])
d$row <- rev(seq_len(nrow(d))) # first row at the top
d$summary <- if (is.null(kind_col)) rep(FALSE, nrow(d)) else as.character(df[[kind_col]][keep]) == "summary"
d$w <- if (is.null(weight_col)) rep(NA_real_, nrow(d)) else df[[weight_col]][keep]
pi_low <- NULL; pi_high <- NULL # the prediction interval, when the result has one
st <- d[!d$summary, ]; pooled <- d[d$summary, ]
st$size <- if (all(is.na(st$w))) 2.5 else 1 + 4 * sqrt(pmax(0, st$w) / max(st$w, na.rm = TRUE))
d$tick <- sprintf("%s %s [%s, %s]", d$label, fmt(d$est), fmt(d$low), fmt(d$high))
diamonds <- do.call(rbind, lapply(seq_len(nrow(pooled)), function(i) with(pooled[i, ],
data.frame(id = i, x = c(low, est, high, est), y = c(row, row + 0.32, row, row - 0.32)))))
p <- ggplot() +
geom_vline(xintercept = reference, colour = ref_col, linetype = "dashed") +
geom_segment(data = st, aes(x = low, xend = high, y = row, yend = row), colour = cs_cat[1], linewidth = 0.5) +
geom_point(data = st, aes(est, row, size = size), shape = 15, colour = cs_cat[1]) +
scale_size_identity() +
scale_y_continuous(breaks = d$row, labels = d$tick, limits = c(0.3, nrow(d) + 0.7)) +
labs(x = est_col, y = NULL) + theme_cs
if (!is.null(pi_low) && nrow(pooled)) p <- p + annotate("segment", x = pi_low, xend = pi_high, y = pooled$row[1], yend = pooled$row[1], colour = ref_col, linetype = "dotted", linewidth = 0.6)
if (!is.null(diamonds)) p <- p + geom_polygon(data = diamonds, aes(x, y, group = id), fill = ref_col)
if (use_log) p <- p + scale_x_log10()
print(p)Needs ggplot2 · reads forest-meta-demo.csv · app theme from the optional codesplashr helper