How to use colorbar with hist2d in matplotlib.pyplot?

I want to do something similar to http://matplotlib.org/examples/pylab_examples/hist2d_log_demo.html , but I read that using pylab for code other than python interactive mode is bad so I would like to do it with using matplotlib.pyplot. However, I cannot figure out how to make this code work with pyplot. Using, pylab, an example

from matplotlib.colors import LogNorm from pylab import * #normal distribution center at x=0 and y=5 x = randn(100000) y = randn(100000)+5 hist2d(x, y, bins=40, norm=LogNorm()) colorbar() show() 

I tried a lot

 import matplotlib.pyplot as plt fig = plt.figure() ax1 = fig.add_subplot(1,1,1) h1 = ax1.hist2d([1,2],[3,4]) 

and from here I tried everything: from plt.colorbar(h1) plt.colorbar(ax1) plt.colorbar(fig) ax.colorbar() , etc. etc., and I cannot get anything to work.

In general, I honestly don’t quite understand the connection between pylab and pyplot, even after reading http://matplotlib.org/faq/usage_faq.html . For example, show() in pylab seems to become plt.show() in pyplot, but somehow the colorbar does not become plt.colorbar() ?

For instance,

+6
source share
2 answers

This should do it:

 from matplotlib.colors import LogNorm import matplotlib.pyplot as plt from numpy.random import randn #normal distribution center at x=0 and y=5 x = randn(100000) y = randn(100000)+5 H, xedges, yedges, img = plt.hist2d(x, y, norm=LogNorm()) extent = [yedges[0], yedges[-1], xedges[0], xedges[-1]] fig = plt.figure() ax = fig.add_subplot(1, 1, 1) im = ax.imshow(H, cmap=plt.cm.jet, extent=extent, norm=LogNorm()) fig.colorbar(im, ax=ax) plt.show() 

Note that the color bar is attached to "fig", not "sub_plot". There are other examples here. Note how you also need to create ScalarMappable using imshow , as described in the API here .

+3
source

As the first argument of the color bar, you need a ScalarMappable object. plt.hist2d returns this as the fourth element of the returned tuple.

 h = hist2d(x, y, bins=40, norm=LogNorm()) colorbar(h[3]) 

Full 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 h = plt.hist2d(x, y, bins=40, norm=LogNorm()) plt.colorbar(h[3]) show() 

enter image description here

+2
source

Source: https://habr.com/ru/post/971637/


All Articles