Capture density with a hexbin plot

Visualize

Capture density with a hexbin plot

Created: Last updated: Read time: 1 min

When scatter points overlap too much, a hexbin plot counts points in hexagonal bins to reveal density. You can draw it easily with matplotlib.hexbin.

import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(42)
session = rng.gamma(shape=3, scale=12, size=1000)   # Session duration (min)
amount = rng.normal(loc=2500, scale=700, size=1000) # Purchase amount (JPY)

fig, ax = plt.subplots(figsize=(6, 4))
hb = ax.hexbin(
    amount,
    session,
    gridsize=18,
    cmap="Blues",
    mincnt=1,
)
ax.set_xlabel("Purchase amount (JPY)")
ax.set_ylabel("Session duration (min)")
ax.set_title("Session duration vs purchase amount (hexbin)")
cb = fig.colorbar(hb, ax=ax, shrink=0.85)
cb.set_label("Count")

fig.tight_layout()

plt.show()

A hexbin plot reveals dense regions at a glance.

Reading tips #

  • Darker hexagons indicate denser regions, making skew and clusters easier to see.
  • Set mincnt to hide bins with too few points.
  • With a colorbar, it works like a heatmap that quantifies volume.