How to add a colorbar for a hist2d plot

后端 未结 1 1212
忘了有多久
忘了有多久 2020-12-30 23:38

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 imp         


        
相关标签:
1条回答
  • 2020-12-31 00:18

    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)
    
    0 讨论(0)
提交回复
热议问题