How to add legend to imshow() in matplotlib

前端 未结 4 1677
忘了有多久
忘了有多久 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:34

    You could use matplotlib.pylab.text to add text to your plot and customize it to look like a legend

    For example:

    import numpy as np
    import matplotlib.cm as cm
    import matplotlib.pylab as plt
    
    raw_data = np.random.random((100, 100))
    fig, ax = plt.subplots(1)
    ax.imshow(raw_data, interpolation='nearest', cmap=cm.gray)
    ax.text(5, 5, 'your legend', bbox={'facecolor': 'white', 'pad': 10})
    plt.show()
    

    which gives you following

    You can check out the matplotlib documentation on text for more details matplotlib text examples

提交回复
热议问题