# Kaplan-Meier Survival Curve in Python with lifelines

> Kaplan-Meier survival analysis in Python with lifelines: fit KaplanMeierFitter on durations and event flags, plot survival curves with confidence intervals per group, read the median survival time, run a log-rank test, and add at-risk counts.

Source: https://www.pythoncharts.com/python/kaplan-meier-survival-curve-python/ | Published: 2026-12-05 | Author: Alex Scott | Category: Python | Tags: lifelines, survival analysis, kaplan-meier, churn, retention, product analytics, matplotlib

To plot a Kaplan-Meier survival curve in Python, fit `lifelines.KaplanMeierFitter` on two columns: how long each user was observed (`duration`) and whether they churned (`event_observed`, 1 or 0). `kmf.plot_survival_function()` then draws the share of users still subscribed at each day, with a confidence band. Users who haven't churned yet are handled for you, which is the reason to use this instead of a retention average.

## Quick Example

This simulates 1,500 subscribers on a monthly or annual plan, then fits and plots one curve per plan. Replace the first block with your own table: one row per user, the days observed, and a 0/1 churn flag.

```python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from lifelines import KaplanMeierFitter
from matplotlib.ticker import PercentFormatter

# --- Sample data: one row per subscriber ---
rng = np.random.default_rng(52)
n = 1500
plan = rng.choice(["Monthly", "Annual"], n, p=[0.65, 0.35])
signup = pd.Timestamp("2025-01-01") + pd.to_timedelta(rng.integers(0, 600, n), unit="D")
true_days = np.ceil(rng.weibull(1.1, n) * np.where(plan == "Annual", 420, 190)).astype(int)  # days until cancelling

end = pd.Timestamp("2026-08-31")  # the day the data was pulled
days_observed = (end - signup).days
df = pd.DataFrame({
    "plan": plan,
    "duration": np.minimum(true_days, days_observed),         # days we watched the subscriber
    "churned": (true_days <= days_observed).astype(int),      # 1 = cancelled, 0 = still subscribed
})

# --- One Kaplan-Meier fit per plan ---
colors = {"Monthly": "#e4572e", "Annual": "#3a6ea5"}
models = {}
fig, ax = plt.subplots(figsize=(9, 5))
for name, group in df.groupby("plan"):
    kmf = KaplanMeierFitter()
    kmf.fit(group["duration"], event_observed=group["churned"], label=name)
    kmf.plot_survival_function(ax=ax, color=colors[name])
    models[name] = kmf

ax.set_title("Share of subscribers still active, by plan")
ax.set_xlabel("Days since signup")
ax.set_ylabel("Subscribers still active")
ax.yaxis.set_major_formatter(PercentFormatter(1))
ax.set_ylim(0, 1.02)
ax.spines[["top", "right"]].set_visible(False)
plt.show()
```

![Kaplan-Meier survival curves for monthly and annual subscribers: the monthly plan curve falls to about 12% by day 365 while the annual plan curve falls to about 45%, each with a shaded confidence band](https://www.pythoncharts.com/python/kaplan-meier-survival-curve-python/images/kaplan-meier-quick-example.png)

Each curve starts at 100% on day 0 and drops a little every time someone cancels. The shaded band is the 95% confidence interval, which widens on the right because fewer subscribers have been watched that long. The monthly plan falls faster, and the two bands separate within the first few weeks.

lifelines 0.30 requires pandas below 3, so the code above is checked in its own environment (pandas 2.3, Matplotlib 3.11). Install it with `pip install lifelines`.

## Why not just average how long users stayed?

Because many users haven't churned yet. A subscriber who signed up two months ago and is still active has a tenure of 60 days *so far*, not 60 days in total. Dropping them biases tenure low. Keeping their 60 as if it were a final value also biases it low. This is called right-censoring, and the `churned = 0` rows in the table are exactly those users.

Kaplan-Meier handles it by keeping a censored user in the "at risk" count for as long as they were observed and removing them afterwards, without counting them as a churn. Compare three ways of summarizing the same data:

```python
summary = pd.DataFrame({
    "avg (churned only)": df[df["churned"] == 1].groupby("plan")["duration"].mean(),
    "avg (everyone)": df.groupby("plan")["duration"].mean(),
    "KM median": pd.Series({p: m.median_survival_time_ for p, m in models.items()}),
}).round(0)
print(summary)
print(df.groupby("plan")["churned"].mean().round(2))
```

```text
        avg (churned only)  avg (everyone)  KM median
Annual                192.0           211.0      342.0
Monthly               131.0           142.0      141.0
plan
Annual     0.45
Monthly    0.73
Name: churned, dtype: float64
```

On the annual plan, 55% of subscribers haven't churned, so both averages (192 and 211 days) land far below the Kaplan-Meier median of 342. On the monthly plan, where 73% have churned, the three numbers are close. The averages only look right when almost everyone has already left; the Kaplan-Meier median estimates how long a typical subscriber lasts either way.

## How do you read the median and survival at a given day?

`kmf.median_survival_time_` is the first day the curve drops to 50% or below. If the curve never reaches 50% within your data, lifelines returns `inf`, which means "more than we could observe". For other points on the curve, `kmf.predict(days)` returns the survival probability, using the last step at or before each day.

```python
checkpoints = [30, 90, 180, 365]
table = pd.DataFrame({name: m.predict(checkpoints) for name, m in models.items()})
print((table * 100).round(1))
```

```text
    Annual  Monthly
30    94.4     88.8
90    86.0     65.7
180   69.8     40.7
365   44.8     12.4
```

This is the table to quote in a report: 90-day retention is read straight off the curve, and unlike "the share of users who are older than 90 days and still active", it uses every user, including those who signed up 20 days ago.

## Add an at-risk table under the plot

A Kaplan-Meier chart is easier to trust when it says how many subscribers each point rests on. `add_at_risk_counts` puts a row of counts under the x-axis, one row per fitted model:

```python
from lifelines.plotting import add_at_risk_counts

fig, ax = plt.subplots(figsize=(9, 5.5))
for name, kmf in models.items():
    kmf.plot_survival_function(ax=ax, color=colors[name], ci_show=False)

add_at_risk_counts(*models.values(), ax=ax, rows_to_show=["At risk"])
ax.set_xlim(0, 540)
ax.set_xlabel("Days since signup")
ax.set_ylabel("Subscribers still active")
ax.yaxis.set_major_formatter(PercentFormatter(1))
ax.spines[["top", "right"]].set_visible(False)
plt.tight_layout()
plt.show()
```

![Kaplan-Meier curves for monthly and annual plans with a table of subscribers at risk below the x-axis at days 0, 100, 200, 300, 400 and 500](https://www.pythoncharts.com/python/kaplan-meier-survival-curve-python/images/kaplan-meier-at-risk.png)

The count shrinks for two reasons: people churn, and people reach the end of the data without churning. Once the numbers under a part of the curve are small, treat the curve there as a rough guide. Zooming the x-axis to where you still have a reasonable number at risk, as `set_xlim(0, 540)` does here, is a common fix.

## Are the two curves really different? Log-rank test

Two curves can look apart and still be noise. The log-rank test compares the whole curves, using the durations and event flags directly:

```python
from lifelines.statistics import logrank_test

monthly = df[df["plan"] == "Monthly"]
annual = df[df["plan"] == "Annual"]
result = logrank_test(
    monthly["duration"], annual["duration"],
    event_observed_A=monthly["churned"], event_observed_B=annual["churned"],
)
print(f"chi-square = {result.test_statistic:.1f}, p = {result.p_value:.2g}")
```

```text
chi-square = 160.7, p = 8.1e-37
```

A p-value this small means the two plans' curves differ by far more than chance would produce. It doesn't say the plan caused the difference. In real data, plan choice is not random, so compare plans with the usual confounding in mind (a [causal inference](https://www.pythoncharts.com/causal-inference/causal-inference-python-guide/) method, or an [A/B test](https://www.pythoncharts.com/ab-testing/ab-testing-python-guide/), if you can randomize). For more than two groups, use `lifelines.statistics.multivariate_logrank_test`.

## Draw the curve in plain Matplotlib

`plot_survival_function()` is quick, but if you want to match a house style, annotate a milestone or put the curve on a shared figure, take the fitted results and draw them yourself. `kmf.survival_function_` and `kmf.confidence_interval_` are DataFrames indexed by day, and the curve is a step function, so use `where="post"`:

```python
fig, ax = plt.subplots(figsize=(9, 5))
for name, kmf in models.items():
    sf = kmf.survival_function_.iloc[:, 0]
    ci = kmf.confidence_interval_
    ax.step(sf.index, sf, where="post", color=colors[name], lw=2.2, label=name)
    ax.fill_between(ci.index, ci.iloc[:, 0], ci.iloc[:, 1], step="post", color=colors[name], alpha=0.15)

offsets = {"Annual": ((14, 10), "left"), "Monthly": ((-8, -16), "right")}  # keep each label off the curves
for name, kmf in models.items():  # mark each plan's 90-day value
    value = float(kmf.predict(90))
    ax.plot(90, value, "o", color=colors[name])
    xytext, ha = offsets[name]
    ax.annotate(f"{value:.0%} at day 90", (90, value), xytext=xytext, ha=ha, textcoords="offset points", color=colors[name])

ax.axvline(90, color="#999999", lw=1, ls="--")
ax.set_xlabel("Days since signup")
ax.set_ylabel("Subscribers still active")
ax.yaxis.set_major_formatter(PercentFormatter(1))
ax.set_ylim(0, 1.02)
ax.set_title("Kaplan-Meier curves drawn with ax.step")
ax.legend(frameon=False)
ax.spines[["top", "right"]].set_visible(False)
plt.show()
```

![Kaplan-Meier survival curves drawn as step functions in Matplotlib with a dashed line at day 90 and labels showing each plan's survival at that day](https://www.pythoncharts.com/python/kaplan-meier-survival-curve-python/images/kaplan-meier-matplotlib.png)

The result is the same curve; only the drawing code is yours. If you'd rather show churn than survival, plot `1 - sf` (or use `kmf.plot_cumulative_density()`).

## Kaplan-Meier curve or cohort retention table?

| | Kaplan-Meier curve | Cohort retention heatmap |
|---|---|---|
| Time axis | Days since signup, continuous | Months or weeks since signup, binned |
| Users not yet churned | Kept in the at-risk count, then dropped when observation ends | Cohorts that haven't reached a period are left blank |
| Output | One smooth curve per group, with a confidence band | A grid of cohort by period |
| Best for | Comparing groups, quoting a median or "retention at day 90" | Spotting changes across signup dates |

They answer different questions, and one doesn't replace the other. The [cohort retention heatmap](https://www.pythoncharts.com/python/cohort-retention-heatmap-python/) shows when a change happened; a Kaplan-Meier curve compares groups.

## Practical Tips

- **Define the event.** "Churned" should mean one specific, dated thing (a cancellation, or 30 days without activity). Whatever the rule is, subscribers who haven't triggered it by the end date are `churned = 0`.
- **Measure duration from the right start.** Duration is the days from signup (or first activity) to the event, or to the data pull date for censored users. A wrong start date shifts the whole curve.
- **Check for negative durations.** A churn date earlier than the signup date is a data error, and `KaplanMeierFitter.fit` accepts it without complaint, so filter these rows out first.
- **Watch the right tail.** After the point where few subscribers are at risk, the steps get large and the band gets wide.
- **Compare groups with the same exposure.** If the annual plan only launched recently, its users can't have been observed for as long, so compare over the same window.

## Similar Topics

- [Cohort Retention Heatmap in Python with pandas and Seaborn](https://www.pythoncharts.com/python/cohort-retention-heatmap-python/)
- [Funnel Charts in Plotly: px.funnel and go.Funnel](https://www.pythoncharts.com/plotly/plotly-funnel-charts/)
- [Line Chart with Confidence Interval in Python](https://www.pythoncharts.com/python/line-chart-with-confidence-interval/)
