How to add a colorbar for a hist2d plot

You are almost there with the 3rd option. You have to pass a mappable object to colorbar so it knows what colormap and limits to give the colorbar. That can be an AxesImage or QuadMesh, etc.

In the case of hist2D, the tuple returned in your h contains that mappable, but also some other things too.

From the docs:

Returns:
The return value is (counts, xedges, yedges, Image).

So, to make the colorbar, we just need the Image.

To fix your code:

from matplotlib.colors import LogNorm
import matplotlib.pyplot as plt
import numpy as np

# normal distribution center at x=0 and y=5
x = np.random.randn(100000)
y = np.random.randn(100000) + 5

fig, ax = plt.subplots()
h = ax.hist2d(x, y, bins=40, norm=LogNorm())
fig.colorbar(h[3], ax=ax)

Alternatively:

counts, xedges, yedges, im = ax.hist2d(x, y, bins=40, norm=LogNorm())
fig.colorbar(im, ax=ax)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)