svgforest
Forest plot
How large are several estimates, how precise, and which exclude the null?
How to read it
- Read each row as an estimate with its interval.
- Check the dashed reference line: an interval crossing it is compatible with no effect.
- Compare interval widths: wider means less precise.
- Callout 1: One estimate: the marker and its interval.
- Callout 2: Reference line: no effect.
- Callout 3: The estimate and its interval, as numbers.
Watch out
- Crossing or not crossing the line isn't the same as large or small: read the size too.
Defaults
- Reference (null) value
- 0
- The value that means no effect, such as 0 for a difference or 1 for a ratio.
- Range -1,000 to 1,000, step 0.1
- Log scale (ratios)
- Off
- Use a log axis, the natural scale for ratios: 2 and ½ sit the same distance from 1.
- Equivalence band ± (0 = none; ratio on log scale)
- 0
- Shade the range of effects you would call practically zero.
- Range 0 to 100, step 0.05
Pinned in the code
- Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing statistical.
- Rows keep the engine's order, top to bottom; the right margin repeats estimate [low, high].
- Ratios (OR, RR, HR, IRR) use a log axis with the reference at 1, so equal ratios look equally far from the null.
- Engine-supplied controls bandLow/bandHigh draw a smallest-effect-of-interest band (TOST / practical significance).
- Marker area ∝ weight when given (meta-analysis style); otherwise all markers are equal.
# Forest plot — Codesplash Chart Lab (recipe "forest")
# controls: reference=0, log=false, bandHalf=0
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-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["subgroup"] = pd.Categorical(df["subgroup"].astype("string"), categories=["All patients", "Age < 65", "Age ≥ 65", "Women", "Men", "Diabetes", "No diabetes"])
_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 levels_of(s):
"""Declared level order (categoricals), else order of first appearance."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [v for v in s.cat.categories if (s == v).any()]
return list(dict.fromkeys(s.dropna().astype(str)))
LABEL = "subgroup"
EST = "mean difference (mmHg)"
LO = "lower"
HI = "upper"
G = None
W = "n"
REFV, LOG, HALF = 0, False, 0 # null value, log axis (ratios), equivalence band ±
d = df.dropna(subset=[LABEL, EST]).reset_index(drop=True)
y = np.arange(len(d))[::-1] # first row at the top
groups = levels_of(d[G]) if G else [None]
fig, ax = plt.subplots(figsize=(8, 0.42 * len(d) + 1.4))
if HALF > 0:
band = (REFV / max(HALF, 1 + 1e-9), REFV * max(HALF, 1 + 1e-9)) if LOG else (REFV - HALF, REFV + HALF)
ax.axvspan(*band, color="#19966e", alpha=0.08, lw=0)
ax.axvline(REFV, color=REF, linestyle="--", linewidth=1)
wmax = d[W].max() if W else 1
for i, row in d.iterrows():
col = PALETTE[groups.index(str(row[G])) % len(PALETTE)] if G else PALETTE[0]
ax.plot([row[LO], row[HI]], [y[i], y[i]], color=col, linewidth=1.6)
size = 24 + 110 * (row[W] / wmax) if W and wmax > 0 else 48 # marker area ∝ weight
ax.scatter(row[EST], y[i], marker="s", s=size, color=col, zorder=3)
ax.set_yticks(y, d[LABEL].astype(str))
if LOG:
ax.set_xscale("log")
ax.set_xlabel(EST)
if G:
for j, g in enumerate(groups):
ax.scatter([], [], marker="s", color=PALETTE[j % len(PALETTE)], label=g)
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads forest-demo.csv · app theme from the optional codesplash helper
# Forest plot — Codesplash Chart Lab (recipe "forest")
# controls: reference=0, log=false, bandHalf=0
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-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["subgroup"] = pd.Categorical(df["subgroup"].astype("string"), categories=["All patients", "Age < 65", "Age ≥ 65", "Women", "Men", "Diabetes", "No diabetes"])
_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 levels_of(s):
"""Declared level order (categoricals), else order of first appearance."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [v for v in s.cat.categories if (s == v).any()]
return list(dict.fromkeys(s.dropna().astype(str)))
LABEL = "subgroup"
EST = "mean difference (mmHg)"
LO = "lower"
HI = "upper"
G = None
W = "n"
REFV, LOG, HALF = 0, False, 0
d = df.dropna(subset=[LABEL, EST]).reset_index(drop=True)
d["_row"] = [f"{i + 1}. {v}" for i, v in enumerate(d[LABEL].astype(str))] # unique rows, first at the top
groups = levels_of(d[G]) if G else [None]
wmax = d[W].max() if W else 1
fig = go.Figure()
for j, g in enumerate(groups):
s = d if g is None else d[d[G].astype(str) == str(g)]
size = (8 + 12 * s[W] / wmax) if W and wmax > 0 else 10
fig.add_scatter(x=s[EST], y=s["_row"], mode="markers", name=g or EST, marker=dict(symbol="square", size=size, color=PALETTE[j % len(PALETTE)]),
error_x=dict(type="data", symmetric=False, array=s[HI] - s[EST], arrayminus=s[EST] - s[LO], thickness=1.6, width=0))
if HALF > 0:
band = (REFV / max(HALF, 1 + 1e-9), REFV * max(HALF, 1 + 1e-9)) if LOG else (REFV - HALF, REFV + HALF)
fig.add_vrect(x0=band[0], x1=band[1], fillcolor="#19966e", opacity=0.08, line_width=0)
fig.add_vline(x=REFV, line=dict(color=REF, dash="dash", width=1))
fig.update_yaxes(categoryorder="array", categoryarray=list(d["_row"])[::-1], title=None)
fig.update_xaxes(type="log" if LOG else "linear", title=EST)
fig.update_layout(showlegend=bool(G))
fig.show()Needs pandas, numpy, plotly · reads forest-demo.csv · app theme from the optional codesplash helper
# Forest plot — Codesplash Chart Lab (recipe "forest")
# controls: reference=0, log=false, bandHalf=0
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-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["subgroup"]] <- factor(df[["subgroup"]], levels = c("All patients", "Age < 65", "Age ≥ 65", "Women", "Men", "Diabetes", "No diabetes"))
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
label_col <- "subgroup"
est_col <- "mean difference (mmHg)"
lo_col <- "lower"
hi_col <- "upper"
g_col <- NULL
w_col <- "n"
refv <- 0; log_x <- FALSE; half <- 0 # null value, log axis (ratios), equivalence band ±
d <- df[!is.na(df[[label_col]]) & !is.na(df[[est_col]]), ]
d <- data.frame(row = factor(seq_len(nrow(d)), levels = rev(seq_len(nrow(d)))), lab = as.character(d[[label_col]]),
est = d[[est_col]], lo = d[[lo_col]], hi = d[[hi_col]], g = if (is.null(g_col)) "" else as.character(d[[g_col]]),
w = if (is.null(w_col)) 1 else d[[w_col]] / max(d[[w_col]], na.rm = TRUE))
band <- if (log_x) c(refv / max(half, 1 + 1e-9), refv * max(half, 1 + 1e-9)) else c(refv - half, refv + half)
p <- ggplot(d, aes(est, row, colour = g)) +
{ if (half > 0) annotate("rect", xmin = band[1], xmax = band[2], ymin = -Inf, ymax = Inf, fill = "#19966e", alpha = 0.08) } +
geom_vline(xintercept = refv, linetype = "dashed", colour = ref_col) +
geom_segment(aes(x = lo, xend = hi, yend = row), linewidth = 0.7) +
geom_point(aes(size = w), shape = 15) +
scale_size_area(max_size = 5, guide = "none") +
scale_y_discrete(labels = rev(d$lab)) +
scale_colour_manual(values = cs_cat, guide = if (is.null(g_col)) "none" else "legend") +
{ if (log_x) scale_x_log10() } +
labs(x = est_col, y = NULL, colour = NULL) + theme_cs
print(p)Needs ggplot2 · reads forest-demo.csv · app theme from the optional codesplashr helper