How do I use colorbar with hist2d in matplotlib.pyplot?

前端 未结 2 1779
暖寄归人
暖寄归人 2021-01-12 07:36

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 interactiv

2条回答
  •  [愿得一人]
    2021-01-12 08:11

    A colorbar needs a ScalarMappable object as its first argument. plt.hist2d returns this as the forth element of the returned tuple.

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

    Complete 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()
    

提交回复
热议问题