How to add legend to imshow() in matplotlib

前端 未结 4 1753
忘了有多久
忘了有多久 2020-12-09 20:06

I am using matplotlib

In plot() or bar(), we can easily put legend, if we add labels to them. but what if it is a contou

4条回答
  •  庸人自扰
    2020-12-09 20:40

    I quote here a solution to a similar question, in case someone is still interested:

    I suppose putting a legend for all values in a matrix only makes sense if there aren't too many of them. So let's assume you have 8 different values in your matrix. We can then create a proxy artist of the respective color for each of them and put them into a legend like this

    import matplotlib.pyplot as plt
    import matplotlib.patches as mpatches
    import numpy as np
    
    # create some data
    data = np.random.randint(0, 8, (5,5))
    # get the unique values from data
    # i.e. a sorted list of all values in data
    values = np.unique(data.ravel())
    
    plt.figure(figsize=(8,4))
    im = plt.imshow(data, interpolation='none')
    
    # get the colors of the values, according to the 
    # colormap used by imshow
    colors = [ im.cmap(im.norm(value)) for value in values]
    # create a patch (proxy artist) for every color 
    patches = [ mpatches.Patch(color=colors[i], label="Level {l}".format(l=values[i]) ) for i in range(len(values)) ]
    # put those patched as legend-handles into the legend
    plt.legend(handles=patches, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0. )
    
    plt.grid(True)
    plt.show()
    

提交回复
热议问题