Hexbin Plots and 2D Histograms in Matplotlib

Show the density of thousands of points with ax.hexbin() and ax.hist2d(), with log color scales, marginal histograms, and per-bin averages.

To show where thousands of points pile up, Matplotlib can count them in bins and color each bin by its count. ax.hexbin(x, y) uses hexagons, and ax.hist2d(x, y) uses rectangles. Pass either result to fig.colorbar() to show what the colors mean.

Quick Example

40,000 simulated taxi trips, distance against fare, as a hexbin plot and a 2D histogram:

import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(21)
n = 40_000
distance = rng.lognormal(mean=1.1, sigma=0.6, size=n)
fare = 4 + 2.6 * distance + rng.normal(0, 1.5 + 0.25 * distance, n)

fig, (left, right) = plt.subplots(
    1, 2, figsize=(10, 4.2), sharey=True, layout="constrained")
extent = [0, 12, 0, 45]

hexes = left.hexbin(distance, fare, gridsize=40, extent=extent,
                    mincnt=1, cmap="viridis")
left.set_title("hexbin")
fig.colorbar(hexes, ax=left, label="Trips")

counts, xedges, yedges, image = right.hist2d(
    distance, fare, bins=40, range=[[0, 12], [0, 45]], cmin=1, cmap="viridis")
right.set_title("hist2d")
fig.colorbar(image, ax=right, label="Trips")

left.set_ylabel("Fare ($)")
fig.supxlabel("Distance (miles)")
plt.show()

Taxi fare against distance as a hexbin plot and as a rectangular 2D histogram, both densest between 1 and 4 miles

The two plots show the same thing: most trips are short and cheap, and fares spread out as distance grows.

extent (for hexbin) and range (for hist2d) limit the binned area. Without them, a few extreme points stretch the bins across mostly empty space.

How Many Bins? gridsize and bins

gridsize is the number of hexagons across the x direction, 100 by default. bins in hist2d() is 10 by default. Neither default suits every dataset, so try a few:

fig, axs = plt.subplots(1, 3, figsize=(10, 3.6), sharey=True, layout="constrained")
for ax, size in zip(axs, [15, 40, 100]):
    ax.hexbin(distance, fare, gridsize=size, extent=extent, mincnt=1)
    ax.set_title(f"gridsize={size}")
plt.show()

Three hexbin plots of the taxi data with grid sizes of 15, 40 and 100, from coarse to speckled

Large bins hide detail; small bins hold so few points that the edges turn into noise. Somewhere around 30 to 60 works for tens of thousands of points.

hist2d() also takes separate counts for each axis, such as bins=[60, 30], or arrays of bin edges.

Hide Empty Bins With mincnt or cmin

By default every bin is drawn, so empty areas get the lowest color of the colormap. mincnt=1 in hexbin() and cmin=1 in hist2d() leave empty bins blank.

Use a Log Color Scale

When one region holds far more points than the rest, a linear color scale leaves the sparse areas indistinguishable. Pass bins="log" to hexbin(), or norm=LogNorm() to hist2d():

from matplotlib.colors import LogNorm

fig, (left, right) = plt.subplots(
    1, 2, figsize=(10, 4.2), sharey=True, layout="constrained")

linear = left.hist2d(distance, fare, bins=50, range=[[0, 12], [0, 45]],
                     cmin=1, cmap="magma_r")
left.set_title("Linear colors")
fig.colorbar(linear[3], ax=left)

logged = right.hist2d(distance, fare, bins=50, range=[[0, 12], [0, 45]],
                      cmin=1, cmap="magma_r", norm=LogNorm())
right.set_title("LogNorm()")
fig.colorbar(logged[3], ax=right)
plt.show()

The same 2D histogram with linear and logarithmic color scales; the log version shows the sparse long trips much more clearly

Color Hexagons by an Average

hexbin() can summarize a third variable. Pass it as C, and reduce_C_function combines the values in each hexagon (the default is the mean). Here the color is the median tip percentage, and mincnt=10 drops hexagons with too few trips to summarize:

tip = np.clip(rng.normal(23 - 1.1 * distance, 4, n), 0, None)

fig, ax = plt.subplots(figsize=(8, 4.8), layout="constrained")
hexes = ax.hexbin(distance, fare, C=tip, reduce_C_function=np.median,
                  gridsize=35, extent=extent, mincnt=10, cmap="coolwarm")
fig.colorbar(hexes, ax=ax, label="Median tip (%)")
ax.set_xlabel("Distance (miles)")
ax.set_ylabel("Fare ($)")
plt.show()

Hexbin plot colored by median tip percentage, high for short trips and falling as distance increases

Add Marginal Histograms

Histograms along the top and right show each variable on its own. Place them with inset_axes() just outside the plot, and share axes so the bins line up:

fig, ax = plt.subplots(figsize=(7.5, 6), layout="constrained")
ax.hexbin(distance, fare, gridsize=40, extent=extent, mincnt=1, cmap="Blues")

top = ax.inset_axes([0, 1.02, 1, 0.22], sharex=ax)
side = ax.inset_axes([1.02, 0, 0.22, 1], sharey=ax)
top.hist(distance, bins=60, range=(0, 12), color="#2171b5")
side.hist(fare, bins=60, range=(0, 45), orientation="horizontal", color="#2171b5")

top.tick_params(labelbottom=False)
side.tick_params(labelleft=False)
ax.set_xlabel("Distance (miles)")
ax.set_ylabel("Fare ($)")
plt.show()

Hexbin plot with a histogram of distance along the top and a histogram of fare on the right, both skewed toward low values

Seaborn builds this layout in one call with jointplot() and kind="hex".

hexbin vs hist2d vs Scatter

Data Use
Up to a few thousand points Scatter plot with alpha
Thousands to millions, general use hexbin(): hexagons have no strong horizontal or vertical grain
Bins that must match meaningful units (hours, dollars) hist2d() with explicit edges
You need the count array hist2d() returns it (rows follow x, so use counts.T with imshow)
A smooth density estimate Seaborn kdeplot()
Hundreds of millions of points Datashader

Similar Topics