优势比森林图

对数刻度上的 logistic 回归优势比,并列附 OR [95% CI] 表格。

优势比森林图

Logistic 回归系数是对数优势;取指数后即为优势比。每个点表示预测变量变化一个单位时结局优势的倍数变化,线段为其 95% 置信区间,OR = 1 处的虚线表示“无效应”。由于比值在对数刻度上是对称的(0.5 与 2 强度相当),x 轴采用对数刻度。右侧一列重复列出这些数字,与论文中的表格如出一辙。

背景设定为 Blakely 与 Warin (2012, Global Economy Journal) 关于欧洲移民决策——自主选择还是模仿——的研究。数据为说明用途而模拟生成,并非论文的数据或结果:n = 2,500 名调查受访者,结局为是否打算移居国外。预测变量为年龄、高等教育、失业、在国外有家人或朋友以及生活满意度。模型用 smf.logit() 拟合,优势比为 params 和 conf_int() 的 np.exp()。

代码及图中文字均为英文。

odds-ratio-forest.py · 66 行
下载 GitHub
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
from matplotlib.ticker import FixedLocator, NullLocator
# Simulated data, set in the context of Blakely & Warin (2012) [blakely2012]

# Data: 2,500 respondents; intention to migrate from a known logistic model
rng = np.random.default_rng(2012)
n = 2500
df = pd.DataFrame({"age10": rng.uniform(1.8, 6.5, n), "tertiary": rng.binomial(1, 0.3, n),
                   "unemployed": rng.binomial(1, 0.1, n), "network": rng.binomial(1, 0.35, n),
                   "satisfaction": rng.integers(1, 11, n)})
eta = (-0.2 - 0.45 * df.age10 + 0.35 * df.tertiary + 0.7 * df.unemployed
       + 0.95 * df.network - 0.12 * df.satisfaction)
df["migrate"] = rng.binomial(1, 1 / (1 + np.exp(-eta)))

model = smf.logit("migrate ~ age10 + tertiary + unemployed + network + satisfaction",
                  data=df).fit(disp=False)

# Odds ratios with 95% CI (intercept dropped), sorted by effect
tab = np.exp(model.conf_int().drop("Intercept")).rename(columns={0: "low", 1: "high"})
tab = tab.assign(OR=np.exp(model.params), p=model.pvalues).sort_values("OR")
labels = {"age10": "Age (per 10 years)", "tertiary": "Tertiary education",
          "unemployed": "Unemployed", "network": "Family/friends abroad",
          "satisfaction": "Life satisfaction (1–10)"}

fig, ax = plt.subplots(figsize=(8.6, 4.6))
y = np.arange(len(tab))
colors = np.where(tab["p"] < 0.05, np.where(tab["OR"] > 1, "#FF9500", "#007AFF"), "#AEAEB2")

ax.axvline(1, color="#8E8E93", lw=1, ls="--", zorder=1)
ax.hlines(y, tab["low"], tab["high"], color=colors, lw=2.5, zorder=2)
ax.scatter(tab["OR"], y, s=80, marker="s", color=colors, edgecolor="white", lw=1.5, zorder=3)

# Right-hand "table" column: OR [95% CI] and p-value
tr = ax.get_yaxis_transform()
top = len(tab) - 0.15
ax.text(1.04, top, "OR [95% CI]", transform=tr, fontsize=10, fontweight="semibold")
ax.text(1.40, top, "p", transform=tr, fontsize=10, fontweight="semibold")
for yi, (_, r) in zip(y, tab.iterrows()):
    ax.text(1.04, yi, f"{r.OR:.2f} [{r.low:.2f}, {r.high:.2f}]", transform=tr,
            va="center", fontsize=10, color="#3A3A3C", family="monospace")
    ax.text(1.40, yi, "<.001" if r.p < .001 else f"{r.p:.3f}".lstrip("0"), transform=tr,
            va="center", fontsize=10, color="#3A3A3C", family="monospace")

ax.set_xscale("log")
ticks = [0.5, 0.67, 1, 1.5, 2, 3]
ax.xaxis.set_major_locator(FixedLocator(ticks))
ax.xaxis.set_minor_locator(NullLocator())
ax.set_xticklabels([f"{t:g}" for t in ticks])
ax.set_xlim(0.45, 3.9)
ax.set_yticks(y, [labels[t] for t in tab.index])
ax.set_ylim(-1.2, len(tab) + 0.1)
ax.grid(axis="x"); ax.grid(axis="y", visible=False)
ax.set_xlabel("Odds ratio of intending to migrate (log scale)")
# Direction hints along the bottom of the panel
for x0, x1, txt, c in [(0.95, 0.75, "lower odds", "#007AFF"), (1.05, 1.33, "higher odds", "#FF9500")]:
    ax.annotate("", (x1, -0.85), (x0, -0.85), arrowprops=dict(arrowstyle="-|>", color=c, lw=1.2))
    ax.text(x1 * (0.97 if x1 < 1 else 1.03), -0.85, txt, color=c, fontsize=9, va="center",
            ha="right" if x1 < 1 else "left")
ax.set_title("Family or friends abroad more than double the odds of planning to move", pad=26)
ax.text(0, 1.02, f"Logistic regression · n = {int(model.nobs):,} respondents (simulated) · "
        f"McFadden pseudo-R² = {model.prsquared:.3f} · LR χ²({model.df_model:.0f}) = "
        f"{model.llr:.0f}, p < .001", transform=ax.transAxes, fontsize=9.5, color="#6E6E73")
plt.show()

图表使用了可选的 PyStatlas 样式:添加 plt.style.use("pystatlas.mplstyle") 即可完全还原其外观。

数据来源

  • Simulated data. Simulated data with a fixed random seed, created for this example.
    No real respondents, documents or measurements: the numbers only illustrate how the chart and its statistics work.
  • Blakely & Warin (2012), the decision to migrate in Europe. Blakely, A., & Warin, T. (2012). Choice or mimetism in the decision to migrate? A European illustration. Global Economy Journal, 12(2). https://doi.org/10.1515/1524-5861.1818
    The example is set in the context of this paper; unless its description says otherwise, the numbers are simulated and are not the paper's data or results.

这些示例用于说明统计方法。除条目另有说明外,其数值均为模拟数据,图表标题描述的是该图在这些模拟数据中呈现的内容——既不是所引论文的结论,也不是作者对实质问题的立场。关于结果、背景和数据,请以此处引用的论文为准。

如何引用

PyStatlas 由 Thierry Warin 创建并维护。如果它对你的工作有所帮助,敬请引用。

Warin, T. (2026). Odds-ratio forest plot. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/regression-models/odds-ratio-forest/

@misc{warin2026statlas,
  author       = {Warin, Thierry},
  title        = {PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences},
  year         = {2026},
  version      = {1.1.0},
  howpublished = {\url{https://warin.ca/pystatlas/}},
  note         = {Source code: https://github.com/warint/pystatlas}
}

更多回归模型图表