Heatmap
Cohort Retention Heatmap
Dark theme cohort analysis showing user retention
Output
Python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.patches import FancyBboxPatch
fig, ax = plt.subplots(figsize=(14, 8), facecolor='#ffffff')
ax.set_facecolor('#ffffff')
np.random.seed(42)
cohorts = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
periods = ['M0', 'M1', 'M2', 'M3', 'M4', 'M5', 'M6']
data = np.zeros((len(cohorts), len(periods)))
for i in range(len(cohorts)):
data[i, 0] = 100
for j in range(1, len(periods)):
data[i, j] = data[i, j-1] * np.random.uniform(0.7, 0.95)
colors = ['#1e293b', '#0c4a6e', '#0284c7', '#38bdf8', '#bae6fd']
cmap = LinearSegmentedColormap.from_list('modern', colors, N=256)
cell_w, cell_h = 0.88, 0.82
for i in range(len(cohorts)):
for j in range(len(periods)):
val = data[i, j]
rect = FancyBboxPatch((j - cell_w/2, i - cell_h/2), cell_w, cell_h,
boxstyle="round,pad=0.02,rounding_size=0.12",
facecolor=cmap((val - 0) / (100 - 0)), edgecolor='#e2e8f0', linewidth=1.5)
ax.add_patch(rect)
ax.text(j, i, f'{val:.0f}%', ha='center', va='center', color='#1e293b', fontsize=10, fontweight='bold')
ax.set_xlim(-0.5, len(periods)-0.5)
ax.set_ylim(-0.5, len(cohorts)-0.5)
ax.set_aspect('equal')
ax.invert_yaxis()
ax.set_xticks(range(len(periods)))
ax.set_yticks(range(len(cohorts)))
ax.set_xticklabels(periods, color='#64748b', fontsize=10, fontweight='500')
ax.set_yticklabels(cohorts, color='#1e293b', fontsize=11, fontweight='500')
sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(0, 100))
cbar = plt.colorbar(sm, ax=ax, shrink=0.8, pad=0.02)
cbar.set_label('Retention %', color='#1e293b', fontsize=11)
cbar.outline.set_edgecolor('#e2e8f0')
plt.setp(plt.getp(cbar.ax.axes, 'yticklabels'), color='#64748b')
for spine in ax.spines.values(): spine.set_visible(False)
ax.tick_params(length=0)
ax.set_title('Cohort Retention Analysis', fontsize=18, color='#1e293b', fontweight='bold', pad=20)
plt.tight_layout()
plt.show()
Library
Matplotlib
Category
Heatmaps & Density
More Heatmap examples
☕