You are almost there with the third option. You must pass the mappable object to the colorbar so that it knows what colormap and limits are to give the colorbar. It could be AxesImage or QuadMesh , etc.
In the case of hist2D tuple returned in h contains mappable , but also some other things.
From docs :
Return: Return value (counts, xedges, yedges, Image).
So, to make a color panel, we just need Image .
To fix your code:
from matplotlib.colors import LogNorm import matplotlib.pyplot as plt import numpy as np
As an alternative:
counts, xedges, yedges, im = ax.hist2d(x, y, bins=40, norm=LogNorm()) plt.colorbar(im, ax=ax)
tom
source share