How to add legend to imshow() in matplotlib

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

    I guess you have to fake your legend, since it requires a line for creating the legend.

    You can do something like this:

    import pylab as pl
    mycmap = pl.cm.jet # for example
    for entry in pl.unique(raw_data):
        mycolor = mycmap(entry*255/(max(raw_data) - min(raw_data)))
        pl.plot(0, 0, "-", c=mycolor, label=mynames[entry])
    
    pl.imshow(raw_data)
    pl.legend()
    

    Of cause this is not very satisfying yet. But maybe you can build something on that.

    [edit: added missing parenthesis]

提交回复
热议问题