How do I use colorbar with hist2d in matplotlib.pyplot?
Question: I want to do something similar to
<http://matplotlib.org/examples/pylab_examples/hist2d_log_demo.html> but I've
read that using pylab for code other than in python interactive mode is bad
practice so I'd like to do this with matplotlib.pyplot. However, I can't
figure out how to make this code work using pyplot. Using, pylab, the example
given is

    
    
    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've tried a lot like

    
    
    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've tried everything from `plt.colorbar(h1)`
`plt.colorbar(ax1)` `plt.colorbar(fig)` `ax.colorbar()` etc etc and I can't
get anything to work.

In general, I'm honestly not really clear on the relationship 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 for some
reason `colorbar` doesn't become `plt.colorbar()`?

For example,


Answer: 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()
    

Notice how colorbar is attached to "fig", not "sub_plot". There are some other
examples of this
[here](http://stackoverflow.com/questions/13784201/matplotlib-2-subplots-1-colorbar).
Notice how you also need to generate a ScalarMappable with `imshow`, as
explained in the API [here](http://matplotlib.org/api/colorbar_api.html).

