How to Make a Forest Plot in Python with Matplotlib

Draw a forest plot of odds ratios with Matplotlib, pool studies with fixed and random effects, and add the table columns journals expect.

A forest plot shows several estimates with their confidence intervals on one shared axis, one row each. In Python, draw it with Matplotlib's ax.errorbar(), use ax.set_xscale("log") for odds or risk ratios, and add a vertical line at the value that means "no effect". This post uses Matplotlib 3.11 and NumPy 2.5.

Quick Example

Eight made-up trials of a physiotherapy program, counting patients who were injured again within a year:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

trials = pd.DataFrame({
    "study": ["Okafor 2015", "Lindqvist 2016", "Moreau 2017", "Tanaka 2018",
              "Alvarez 2019", "Novak 2021", "Haddad 2022", "Kowalski 2024"],
    "events_program": [8, 24, 4, 31, 12, 14, 6, 63],
    "n_program": [60, 120, 35, 240, 90, 150, 55, 410],
    "events_control": [14, 21, 6, 44, 11, 41, 12, 76],
    "n_control": [62, 118, 34, 236, 92, 148, 54, 405],
})

# Log odds ratio and its standard error for each trial
a = trials.events_program
b = trials.n_program - a
c = trials.events_control
d = trials.n_control - c
trials["log_or"] = np.log(a * d / (b * c))
trials["se"] = np.sqrt(1 / a + 1 / b + 1 / c + 1 / d)
trials["or"] = np.exp(trials.log_or)
trials["low"] = np.exp(trials.log_or - 1.96 * trials.se)
trials["high"] = np.exp(trials.log_or + 1.96 * trials.se)

y = np.arange(len(trials))

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.errorbar(trials["or"], y,
            xerr=[trials["or"] - trials.low, trials.high - trials["or"]],
            fmt="s", color="#14532d", ecolor="#555555", capsize=3)
ax.axvline(1, color="black", ls="--", lw=1)
ax.set_xscale("log")
ax.set_xticks([0.1, 0.25, 0.5, 1, 2, 4], ["0.1", "0.25", "0.5", "1", "2", "4"])
ax.minorticks_off()
ax.set_yticks(y, trials.study)
ax.invert_yaxis()
ax.set_xlabel("Odds ratio (below 1 favors the program)")
plt.show()

Forest plot of odds ratios for eight trials, most below the dashed line at 1 but with intervals that cross it

On a log scale, an odds ratio of 0.5 and one of 2 sit the same distance from 1, and the intervals look symmetric.

Pool the studies

An inverse-variance meta-analysis gives precise studies more weight. A fixed effect model assumes one true effect. A random effects model lets the true effect vary between studies; the DerSimonian-Laird method estimates that variance (tau2).

def pool(effect, se, tau2=0.0):
    w = 1 / (se**2 + tau2)
    estimate = np.sum(w * effect) / w.sum()
    return estimate, np.sqrt(1 / w.sum()), w / w.sum()

fixed, fixed_se, w_fixed = pool(trials.log_or, trials.se)

# Heterogeneity
w = 1 / trials.se**2
Q = np.sum(w * (trials.log_or - fixed) ** 2)
dof = len(trials) - 1
tau2 = max(0, (Q - dof) / (w.sum() - np.sum(w**2) / w.sum()))
I2 = max(0, (Q - dof) / Q)

rand, rand_se, weights = pool(trials.log_or, trials.se, tau2)

for name, est, se in [("fixed", fixed, fixed_se), ("random", rand, rand_se)]:
    print(f"{name:6s} OR {np.exp(est):.2f} "
          f"({np.exp(est - 1.96 * se):.2f} to {np.exp(est + 1.96 * se):.2f})")
print(f"Q = {Q:.1f}, I² = {I2:.0%}, tau² = {tau2:.3f}")
fixed  OR 0.68 (0.54 to 0.85)
random OR 0.65 (0.46 to 0.91)
Q = 13.2, I² = 47%, tau² = 0.103

Both models find lower odds of re-injury with the program. The random effects interval is wider because it includes the variation between trials: an I² of 47% says about half of the spread is more than chance would produce.

statsmodels can check the arithmetic:

from statsmodels.stats.meta_analysis import combine_effects

result = combine_effects(trials.log_or.to_numpy(),
                         trials.se.to_numpy() ** 2, method_re="dl",
                         row_names=list(trials.study))
print(np.exp(result.summary_frame().loc[
    ["fixed effect", "random effect"], ["eff", "ci_low", "ci_upp"]]).round(2))
                eff  ci_low  ci_upp
fixed effect   0.68    0.54    0.85
random effect  0.65    0.46    0.91

In statsmodels 0.15.0, I found that when Q is smaller than the number of studies minus one, this function returned a negative tau2 and NaN random effects intervals. Check result.tau2, or clip it at zero as the code above does.

Add the pooled diamond and study weights

The diamond's center is the pooled estimate and its tips are the ends of the confidence interval. Square areas show each study's weight.

from matplotlib.patches import Polygon

def forest_axes(ax):
    ax.errorbar(trials["or"], y,
                xerr=[trials["or"] - trials.low, trials.high - trials["or"]],
                fmt="none", ecolor="#555555", lw=1.2)
    ax.scatter(trials["or"], y, s=weights * 900, marker="s", color="#14532d",
               zorder=3)
    center = np.exp(rand)
    left, right = np.exp(rand + np.array([-1.96, 1.96]) * rand_se)
    row = len(trials) + 0.3
    ax.add_patch(Polygon([(left, row), (center, row - 0.35),
                          (right, row), (center, row + 0.35)], color="#b45309"))
    ax.axvline(1, color="black", ls="--", lw=1)
    ax.axvline(center, color="#b45309", ls=":", lw=1)
    ax.set_xscale("log")
    ax.set_xlim(0.1, 4)
    ax.set_xticks([0.1, 0.25, 0.5, 1, 2, 4],
                  ["0.1", "0.25", "0.5", "1", "2", "4"])
    ax.minorticks_off()
    ax.set_ylim(row + 0.8, -0.8)
    return center, left, right, row

fig, ax = plt.subplots(figsize=(8, 4.8))
*_, row = forest_axes(ax)
ax.set_yticks([*y, row], [*trials.study, "Pooled (random effects)"])
ax.set_xlabel("Odds ratio (below 1 favors the program)")
plt.show()

Forest plot with squares sized by study weight and an orange diamond for the pooled odds ratio, entirely below 1

Add columns of numbers

Journals usually print event counts and estimates beside the plot. Place text with ax.get_yaxis_transform(), where x is in Axes units (0 is the left edge) and y is in data units.

fig, ax = plt.subplots(figsize=(11, 5))
fig.subplots_adjust(left=0.36, right=0.76, top=0.88, bottom=0.14)
center, left, right, row = forest_axes(ax)
ax.set_yticks([])
ax.spines[["left", "right", "top"]].set_visible(False)

def write(x, yy, text, **kwargs):
    ax.text(x, yy, text, transform=ax.get_yaxis_transform(), va="center",
            fontsize=10, **kwargs)

header = -1.3
write(-0.72, header, "Study", fontweight="bold")
write(-0.34, header, "Program", ha="center", fontweight="bold")
write(-0.12, header, "Control", ha="center", fontweight="bold")
write(1.04, header, "OR (95% CI)", fontweight="bold")
write(1.5, header, "Weight", ha="right", fontweight="bold")

for i, r in enumerate(trials.to_dict("records")):
    write(-0.72, i, r["study"])
    write(-0.34, i, f'{r["events_program"]}/{r["n_program"]}', ha="center")
    write(-0.12, i, f'{r["events_control"]}/{r["n_control"]}', ha="center")
    write(1.04, i, f'{r["or"]:.2f} ({r["low"]:.2f}–{r["high"]:.2f})')
    write(1.5, i, f"{weights[i]:.0%}", ha="right")

write(-0.72, row, "Pooled", fontweight="bold")
write(1.04, row, f"{center:.2f} ({left:.2f}–{right:.2f})", fontweight="bold")
write(1.5, row, "100%", ha="right", fontweight="bold")
ax.set_xlabel("Odds ratio (below 1 favors the program)")
plt.show()

Publication style forest plot with study names, event counts, odds ratios with intervals and weights in columns around the plot, and a pooled diamond

Other uses for forest plots

Any list of estimates with intervals works. For regression coefficients or differences, keep a linear axis and put the reference line at 0. For A/B test metrics, see the forest plot of 20 metrics in multiple testing corrections for A/B tests.

Practical tips

  • State which direction favors which group on the axis label.
  • Report heterogeneity with the pooled estimate. A pooled number hides studies that disagree.
  • With few studies, DerSimonian-Laird intervals tend to be too narrow. For real reviews, consider other estimators and interval methods, and follow a reporting standard.
  • A zero in any cell breaks the log odds ratio. Adding 0.5 to each cell of that study is a common correction.
  • Sort rows by something meaningful, here publication year.

Similar Topics