Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a colorbar for a hist2d plot

Well, I know how to add a colour bar to a figure, when I have created the figure directly with 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 does the following not work, and what would I need to add to the call of colorbar(..) to make it work.

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' 
like image 347
Thomas Möbius Avatar asked Feb 22 '17 09:02

Thomas Möbius


People also ask

How do I add Colorbar to Matlab?

To move the colorbar to a different tile, set the Layout property of the colorbar. To display the colorbar in a location that does not appear in the table, use the Position property to specify a custom location. If you set the Position property, then MATLAB® sets the Location property to 'manual' .

How do I change the Colorbar scale in Matplotlib?

Use the matpltolib. pyplot. clim() Function to Set the Range of Colorbar in Matplotlib. The clim() function can be used to control the range of the colorbar by setting the color limits of the plot, which are used for scaling.


1 Answers

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) 
like image 197
tmdavison Avatar answered Oct 12 '22 10:10

tmdavison