How to add color bar to hist2d chart

Well, I know how to add a color shape to a shape when I created the shape directly from matplotlib.pyplot.plt .

 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 # This works plt.figure() plt.hist2d(x, y, bins=40, norm=LogNorm()) plt.colorbar() 

But why the following does not work and what I need to add to the colorbar(..) call so that it works.

 fig, ax = plt.subplots() ax.hist2d(x, y, bins=40, norm=LogNorm()) fig.colorbar() # TypeError: colorbar() missing 1 required positional argument: 'mappable' fig, ax = plt.subplots() ax.hist2d(x, y, bins=40, norm=LogNorm()) fig.colorbar(ax) # AttributeError: 'AxesSubplot' object has no attribute 'autoscale_None' fig, ax = plt.subplots() h = ax.hist2d(x, y, bins=40, norm=LogNorm()) plt.colorbar(h, ax=ax) # AttributeError: 'tuple' object has no attribute 'autoscale_None' 
+7
python matplotlib
source share
1 answer

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 # 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()) plt.colorbar(h[3], ax=ax) 

As an alternative:

 counts, xedges, yedges, im = ax.hist2d(x, y, bins=40, norm=LogNorm()) plt.colorbar(im, ax=ax) 
+7
source share

All Articles