Kaplan–Meier 生存曲线

专利从申请到授权的时间:国内与国外申请人对比,附 log-rank 检验和风险数表。

Kaplan–Meier 生存曲线

Kaplan–Meier 估计量将随访时间——有的以事件结束,有的被删失——转换为一条阶梯曲线,表示“存活”超过每个时间点的概率。阴影带为逐点 95% 置信区间,短竖线标记被删失的申请,虚线从 50% 处下落至各组的中位生存时间。下方的表格给出仍处于风险中的数量,据此可以判断每条曲线的尾部有多少数据支撑。

背景为 Vorreuther 和 Warin (2021, Data in Brief),一个关于中国制药业专利关联度与授权速度的数据集。此处数据为说明用途的模拟数据,并非论文的数据或结果:400 件医药专利申请,以自申请起的月数计时;事件为授权,观察结束时仍在审查中的申请作删失处理。曲线来自 KaplanMeierFitter,比较来自 logrank_test。

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

kaplan-meier.py · 62 行
下载 GitHub
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from lifelines import KaplanMeierFitter
from lifelines.statistics import logrank_test
# Simulated data, set in the context of Vorreuther & Warin (2021) [vorreuther2021]

# Data: months from filing to grant of 400 patent applications (shared generator)
rng = np.random.default_rng(2021)
n = 400
df = pd.DataFrame({"foreign": rng.integers(0, 2, n), "university": (rng.random(n) < 0.25).astype(int),
                   "claims": rng.poisson(12, n), "relatedness": rng.beta(2, 4, n).round(2)})
lp = 0.6 * df.foreign - 0.04 * (df.claims - 12) + 2.0 * (df.relatedness - 0.33) - 0.35 * df.university
grant = 40 * rng.weibull(2, n) * np.exp(-lp / 2)        # Weibull PH: higher lp, faster grant
cens = rng.uniform(24, 96, n)                           # end of observation window
df["months"], df["granted"] = np.minimum(grant, cens).round(1), (grant <= cens).astype(int)

groups = {"Domestic": df[df.foreign == 0], "Foreign": df[df.foreign == 1]}
colors = ["#007AFF", "#FF9500"]
ticks = np.arange(0, 97, 12)
fig, (ax, tab) = plt.subplots(2, 1, figsize=(8, 6.2), sharex=True,
                              gridspec_kw=dict(height_ratios=[4.2, 1]))

# Kaplan–Meier fit per group: step curve, CI band, censoring ticks, median line, risk table
for k, ((name, d), c) in enumerate(zip(groups.items(), colors)):
    km = KaplanMeierFitter().fit(d.months, d.granted, label=name)
    sf, ci = km.survival_function_[name], km.confidence_interval_
    ax.step(sf.index, sf, where="post", color=c, lw=2, label=f"{name} applicants (n = {len(d)})")
    ax.fill_between(ci.index, ci.iloc[:, 0], ci.iloc[:, 1], step="post", color=c, alpha=0.12, lw=0)
    cm = d.loc[d.granted == 0, "months"]
    ax.plot(cm, km.survival_function_at_times(cm), "|", color=c, ms=7, mew=1.2)
    med = km.median_survival_time_
    ax.plot([med, med], [0, 0.5], ls="--", lw=1, color=c)
    ax.text(med, 0.02, f" {med:.0f} mo", color=c, fontsize=9.5, fontweight="semibold", ha="left")
    for t in ticks:
        tab.text(t, 1 - k, (d.months >= t).sum(), ha="center", va="center", color=c, fontsize=10)

ax.axhline(0.5, color="#8E8E93", lw=1, ls="--", zorder=1)
ax.set(ylim=(0, 1.02), xlim=(-3, 99), ylabel="Probability still pending", xlabel="Months since filing")
ax.tick_params(labelbottom=True)
ax.yaxis.set_major_formatter(plt.matplotlib.ticker.PercentFormatter(1))
ax.legend(loc="upper right")

# Log-rank test
dom, fgn = groups["Domestic"], groups["Foreign"]
lr = logrank_test(dom.months, fgn.months, dom.granted, fgn.granted)
p_txt = "p < .001" if lr.p_value < 0.001 else f"p = {lr.p_value:.3f}"
ax.set_title("Time to grant for two applicant groups, with a log-rank test", pad=26)
ax.text(0, 1.02, f"Log-rank χ²(1) = {lr.test_statistic:.1f}, {p_txt}  ·  Kaplan–Meier with 95% CI  ·  "
        f"n = {n} applications (simulated), {df.granted.sum()} grants", transform=ax.transAxes,
        fontsize=9.5, color="#6E6E73")

# Risk table styling
tab.set(ylim=(-0.5, 1.5), xticks=ticks)
tab.tick_params(labelbottom=False)
tab.set_yticks([1, 0], list(groups))
for lbl, c in zip(tab.get_yticklabels(), colors):
    lbl.set_color(c)
tab.grid(False)
tab.spines[["left", "bottom"]].set_visible(False)
tab.set_title("Number at risk", fontsize=10, fontweight="normal", color="#6E6E73", pad=4)
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.
  • Vorreuther & Warin (2021), patent velocity in China's pharmaceutical industry. Vorreuther, C. M., & Warin, T. (2021). Patent relatedness and velocity in the Chinese pharmaceutical industry: A dataset of Jaccard similarities. Data in Brief, 35, 106814. https://doi.org/10.1016/j.dib.2021.106814
    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). Kaplan–Meier curves. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/survival/kaplan-meier/

@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}
}

更多生存分析图表