2D Histogram
Session Engagement Analysis
User session duration vs page views density
Output
Python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LinearSegmentedColormap
# Web analytics data
np.random.seed(42)
n_sessions = 12000
# Session duration (minutes) - log-normal
duration = np.random.lognormal(2.5, 0.8, n_sessions)
duration = np.clip(duration, 0.5, 60)
# Page views correlate with duration
base_views = 1 + duration * 0.4
page_views = base_views + np.random.exponential(2, n_sessions)
page_views = np.clip(page_views, 1, 50)
# Analytics dark theme
plt.style.use('dark_background')
fig, ax = plt.subplots(figsize=(10, 8))
fig.patch.set_facecolor('#0d1117')
ax.set_facecolor('#0d1117')
# Custom colormap - analytics teal-cyan
colors = ['#0d1117', '#0a2030', '#0a3545', '#0a4a5a', '#1a6a70',
'#2a8a85', '#4aaaa0', '#6acab5', '#8aeaca', '#aaffdf', '#d0fff0']
cmap = LinearSegmentedColormap.from_list('analytics', colors, N=256)
# 2D histogram
h = ax.hist2d(duration, page_views, bins=[50, 40], cmap=cmap, cmin=1)
# Engagement thresholds
ax.axvline(x=10, color='#4aaaa0', linestyle='--', alpha=0.6, linewidth=1.5, label='Engaged (>10min)')
ax.axhline(y=10, color='#6acab5', linestyle=':', alpha=0.6, linewidth=1.5, label='Deep Browse (>10 pages)')
# High value zone
from matplotlib.patches import Rectangle
high_value = Rectangle((15, 15), 45, 35, fill=False, edgecolor='#aaffdf',
linewidth=2, linestyle='-', alpha=0.6)
ax.add_patch(high_value)
ax.text(35, 45, 'High Value Users', fontsize=10, color='#aaffdf', ha='center', alpha=0.8)
# Styled colorbar
cbar = plt.colorbar(h[3], ax=ax, pad=0.02, shrink=0.85)
cbar.ax.set_facecolor('#0d1117')
cbar.set_label('Session Count', fontsize=11, color='#a0d0c0', labelpad=10)
cbar.ax.yaxis.set_tick_params(color='#a0d0c0')
cbar.outline.set_edgecolor('#2a4040')
plt.setp(plt.getp(cbar.ax.axes, 'yticklabels'), color='#a0d0c0', fontsize=9)
# Labels
ax.set_xlabel('Session Duration (minutes)', fontsize=13, color='#a0d0c0', fontweight='600', labelpad=10)
ax.set_ylabel('Page Views', fontsize=13, color='#a0d0c0', fontweight='600', labelpad=10)
ax.set_title('User Engagement Analysis', fontsize=16, color='white', fontweight='bold', pad=20)
# Style axes
ax.tick_params(colors='#80b0a0', labelsize=10, length=0)
for spine in ax.spines.values():
spine.set_visible(False)
ax.legend(loc='upper right', fontsize=9, facecolor='#1a2a30', edgecolor='#2a4040',
labelcolor='#a0d0c0', framealpha=0.9)
plt.tight_layout()
plt.show()
Library
Matplotlib
Category
Statistical
More 2D Histogram examples
☕