# Cohort Retention Heatmap in Python with pandas and Seaborn

> Cohort retention analysis in Python: group users by first activity month, count unique active users per month since signup with pandas groupby and unstack, divide by cohort size, and plot the triangle as an annotated Seaborn heatmap.

Source: https://www.pythoncharts.com/python/cohort-retention-heatmap-python/ | Published: 2026-12-05 | Author: Alex Scott | Category: Python | Tags: pandas, seaborn, heatmap, cohort analysis, retention, product analytics

To make a cohort retention heatmap in Python, label each user with the month of their first event, count the unique users still active in each later month with `groupby(["cohort", "period"])["user_id"].nunique()`, divide each row by its month-0 count, and pass the result to `sns.heatmap(..., annot=True, fmt=".0%")`.

## Quick Example

This builds a fake events log (6,000 users, one row per event), turns it into a cohort-by-month retention table, and draws it. Swap the first block for your own `events` DataFrame with a `user_id` column and a `date` column.

```python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

# --- Sample events log: one row per user event ---
rng = np.random.default_rng(31)
n_users = 6000
end = pd.Timestamp("2026-11-30")  # last day of data

# One signup date per user, spread over Jan 1 to Nov 30, 2026
signup = pd.Timestamp("2026-01-01") + pd.to_timedelta(rng.integers(0, 334, n_users), unit="D")

# Chance a user is active k months after signup (k = 0 is the signup month)
base = np.array([1, .45, .34, .29, .26, .24, .22, .21, .20, .19, .185])
lift = np.where(signup >= "2026-06-01", 1.25, 1.0)  # onboarding change shipped in June
active = rng.random((n_users, 11)) < np.clip(np.outer(lift, base), 0, 1)
active[:, 0] = True

user_id, k = np.nonzero(active)
month_start = (signup[user_id].to_period("M") + k).to_timestamp()
days_in_month = (month_start + pd.offsets.MonthEnd(0)).day
offset = (rng.random(len(k)) * days_in_month).astype(int)
date = np.where(k == 0, signup[user_id], month_start + pd.to_timedelta(offset, unit="D"))
events = pd.DataFrame({"user_id": user_id, "date": pd.to_datetime(date)})
events = events.loc[events["date"] <= end]
events = events.loc[events.index.repeat(rng.integers(1, 4, len(events)))]  # several events per active month

# --- Cohort table ---
events["month"] = events["date"].dt.to_period("M")
events["cohort"] = events.groupby("user_id")["month"].transform("min")  # month of first event
events["period"] = (
    (events["month"].dt.year - events["cohort"].dt.year) * 12
    + (events["month"].dt.month - events["cohort"].dt.month)
)  # months since the first event

counts = events.groupby(["cohort", "period"])["user_id"].nunique().unstack("period")
retention = counts.div(counts[0], axis=0)  # share of each cohort still active

# --- Heatmap ---
labels = [f"{c.strftime('%b %Y')}  (n={int(n):,})" for c, n in counts[0].items()]
fig, ax = plt.subplots(figsize=(10, 6))
sns.heatmap(
    retention, annot=True, fmt=".0%", cmap="YlGnBu", vmin=0, vmax=0.6,
    yticklabels=labels, cbar_kws={"label": "Share of cohort active"},
    linewidths=1, linecolor="white", ax=ax,
)
ax.set_title("Monthly user retention by signup cohort")
ax.set_xlabel("Months since first event")
ax.set_ylabel("Cohort (users)")
plt.show()
```

![Cohort retention heatmap with signup months as rows and months since signup as columns, forming a triangle where the newest cohorts have the fewest columns and later cohorts retain more users in month one](https://www.pythoncharts.com/python/cohort-retention-heatmap-python/images/cohort-retention-quick-example.png)

Each row is a signup cohort, each column is the number of months since that cohort's first event, and each cell is the share of the cohort that was active in that month. Column 0 is always 100%. The triangle shape is real: a user who signed up in October can't have a month-10 value yet, so those cells stay empty. The code targets pandas 3.1, Seaborn 0.13 and Matplotlib 3.11.

## How the cohort table is built

The retention table comes from three pandas steps:

1. **Assign a cohort.** `groupby("user_id")["month"].transform("min")` gives every event row the month of that user's first event.
2. **Compute the period.** The number of months between the event's month and the cohort month. Subtracting `year * 12 + month` values keeps this a plain integer, which is what you want on the heatmap's x-axis.
3. **Count unique users.** `nunique()` per `(cohort, period)`, then `unstack("period")` to turn periods into columns.

Here are the first rows of the absolute counts, before dividing:

```python
print(counts.iloc[:4, :5].astype(int))
```

```text
period     0    1    2    3    4
cohort                          
2026-01  554  260  196  171  157
2026-02  453  184  164  132  134
2026-03  503  230  189  166  125
2026-04  534  230  163  168  135
```

Dividing every row by its first column (`counts.div(counts[0], axis=0)`) turns those into percentages. Cohort sizes vary from month to month, so percentages are what let you compare a 453-user cohort with a 592-user one.

Count `user_id` with `nunique()`, not `count()`. In the sample log, active users have one to three events a month, so counting rows would inflate retention in months where people were busy.

## What does the heatmap tell you?

Read it two ways. Down a column, you compare cohorts at the same age. Across a row, you see one cohort decay.

In this sample, the January to May cohorts keep an average of 44% of users in month 1, and the June to October cohorts keep 57%. That step shows up as a change in color down the month-1 column, right at the June row. A shift that lines up with a calendar month, regardless of cohort age, is usually something you shipped (here, an onboarding change). A diagonal band that cuts across several cohorts at the same calendar month points to something outside the product, like a holiday or an outage.

## Why set vmax on the color scale?

Month 0 is always 100%, so with the default scale it takes up the whole dark end of the colormap and the interesting part of the table (everything from 15% to 60%) shares the pale end. Capping the scale with `vmax` spends the color range where the differences are. The annotations still show the true values, and the 100% cells simply saturate.

```python
short_labels = [c.strftime("%b %Y") for c in retention.index]
fig, axes = plt.subplots(1, 2, figsize=(12, 5), sharey=True)
for ax, vmax, title in [(axes[0], None, "Default scale (max is 100%)"), (axes[1], 0.6, "vmax=0.6")]:
    sns.heatmap(
        retention, annot=True, fmt=".0%", cmap="YlGnBu", vmin=0, vmax=vmax,
        yticklabels=short_labels, annot_kws={"fontsize": 7}, cbar=False, linewidths=1, linecolor="white", ax=ax,
    )
    ax.set_title(title)
    ax.set_xlabel("Months since first event")
    ax.set_ylabel("")
axes[0].set_ylabel("Cohort")
plt.tight_layout()
plt.show()
```

![Two cohort retention heatmaps side by side; the left uses the default color scale where only month 0 is dark, the right caps the scale at 60% so differences between cohorts are visible](https://www.pythoncharts.com/python/cohort-retention-heatmap-python/images/cohort-retention-vmax.png)

If you drop the month-0 column (`retention.drop(columns=0)`), the scale adjusts on its own and you don't need `vmax`. Keep it if you want the reader to see that every cohort starts at 100%.

## Plot retention curves for each cohort

Heatmaps are good at spotting patterns across cohorts, but a line chart is better for the shape of the decay and for putting a number on the difference. Draw one line per cohort and color them by the group you care about. Here the cohorts before and after the June change get different colors, with a bold average line for each group:

```python
fig, ax = plt.subplots(figsize=(9, 5))
groups = {"Jan to May cohorts": (retention.index < "2026-06", "#8a8f98"),
          "Jun to Oct cohorts": ((retention.index >= "2026-06") & (retention.index < "2026-11"), "#1f9d8a")}

for name, (mask, color) in groups.items():
    subset = retention[mask]
    for _, row in subset.iterrows():
        ax.plot(row.dropna().index, row.dropna() * 100, color=color, alpha=0.3, lw=1)
    mean = subset.mean()  # average over the cohorts that have reached each month
    ax.plot(mean.dropna().index, mean.dropna() * 100, color=color, lw=3, label=name)

ax.set_xlabel("Months since first event")
ax.set_ylabel("Users active (%)")
ax.set_title("Retention curves: before vs after the June onboarding change")
ax.set_ylim(0, 105)
ax.legend()
ax.spines[["top", "right"]].set_visible(False)
plt.show()
```

![Retention curves for each signup cohort, grey for January to May cohorts and teal for June to October cohorts, with bold average lines showing the later cohorts retaining more users at every month](https://www.pythoncharts.com/python/cohort-retention-heatmap-python/images/cohort-retention-curves.png)

The average line stops where the youngest cohort in the group runs out of data. Averaging a column that only has a few cohorts left, such as month 6 for June, mixes in less data than month 1 does, so don't over-read the right end of the curve.

## Which retention definition should you use?

The table above is **classic (N-month) retention**: the share of a cohort active *in* month N. Two other definitions are common, and they give different numbers from the same events.

| Definition | Counts a user in month N if | Can it go up? | Use it for |
|---|---|---|---|
| Classic (N-month) | active during month N | Yes, when users return | Products used regularly, such as messaging or social apps |
| Rolling (unbounded) | active in month N or any later month | No, only falls | Products with long gaps between uses, such as travel or tax tools |
| Cumulative | active at least once up to month N | Only rises | Activation and "ever came back" questions |

Rolling retention needs the last period each user was active:

```python
last_period = events.groupby("user_id")["period"].max()
user_cohort = events.groupby("user_id")["cohort"].first()

rolling = pd.DataFrame({k: (last_period >= k).groupby(user_cohort).mean() for k in range(11)})
rolling = rolling.where(retention.notna())  # keep the empty triangle
print(rolling.iloc[0].round(2).tolist())
print(retention.iloc[0].round(2).tolist())
```

```text
[1.0, 0.96, 0.92, 0.89, 0.83, 0.76, 0.69, 0.59, 0.48, 0.34, 0.19]
[1.0, 0.47, 0.35, 0.31, 0.28, 0.24, 0.23, 0.21, 0.2, 0.19, 0.19]
```

Classic retention mostly falls but can tick up when users return: the February cohort is at 29% in month 3 and 30% in month 4. For the January cohort, rolling retention is 96% in month 1 against 47% for classic, and the two meet at month 10, because the last month has no later months to add. Rolling is never lower than classic and never rises, since it also counts everyone who is active later. State which definition you used in the chart title or subtitle, since people compare these numbers across companies without checking.

## Can you use weekly cohorts instead of monthly?

Yes. Group by the week of a user's first event and count weeks since then. Weekly cohorts give you more rows, so they react faster to a release, and each cohort is smaller and noisier. Drop the current partial week before you compute, or the newest column will look like a collapse.

```python
complete = events[events["date"] < "2026-11-30"]  # Nov 30 is a Monday, so the last week is just one day

week = complete["date"].dt.to_period("W")
cohort_week = complete.groupby("user_id")["date"].transform("min").dt.to_period("W")
period_week = (week.dt.start_time - cohort_week.dt.start_time).dt.days // 7

weekly = (
    complete.assign(cohort=cohort_week, period=period_week)
    .groupby(["cohort", "period"])["user_id"]
    .nunique()
    .unstack("period")
)
weekly_retention = weekly.div(weekly[0], axis=0)
print(weekly_retention.shape)
```

```text
(48, 48)
```

With 48 cohorts, annotate nothing (`annot=False`) and let the colors carry it, or show only the last 12 cohorts. For day-based retention (D1, D7, D30), use `(date - first_date).dt.days` as the period instead.

## Practical Tips

- **Leave incomplete cells empty.** A cohort that hasn't reached month N yet has no value there, which is why the `NaN` cells stay blank. Filling them with 0 draws a fake cliff along the diagonal.
- **Show cohort sizes.** A 70% retention on 40 users is not the same evidence as 70% on 4,000. Putting `n=` in the row labels, as in the quick example, keeps small cohorts honest.
- **Define "active" before you plot.** Any event, a login, and a key action (a purchase, a message sent) give very different retention curves. Filter `events` to the action that matters first.
- **Use one cohort definition.** Cohort by first event, not by account creation date, if some users create accounts and never do anything. The two can differ.
- **Compare groups with a survival curve.** When you want one curve per plan or channel and a median lifetime, a [Kaplan-Meier survival curve](https://www.pythoncharts.com/python/kaplan-meier-survival-curve-python/) uses every user, including those who signed up recently.
- **Compare against a funnel.** Retention starts after activation. If most users never get that far, start with a [funnel chart](https://www.pythoncharts.com/plotly/plotly-funnel-charts/).

## Similar Topics

- [How to Create Heatmaps in Matplotlib](https://www.pythoncharts.com/matplotlib/heatmaps-matplotlib/)
- [Funnel Charts in Plotly: px.funnel and go.Funnel](https://www.pythoncharts.com/plotly/plotly-funnel-charts/)
- [How to Style Seaborn Heatmaps (Annotate Values, Masking)](https://www.pythoncharts.com/seaborn/seaborn-style-heatmaps/)
