rankthefirst rankthefirst - 2 months ago 32
Python Question

How to add legend to imshow() in matplotlib

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
contourf()
or
imshow()


I know there is a
colorbar()
which can present the color range, but it is not satisfied. I want such a legend which have names(labels).

enter image description here

For what I can think of is that, add labels to each element in the matrix, then ,try legend(), to see if it works, but how to add label to the element, like a value??

in my case, the raw data is like:

1,2,3,3,4
2,3,4,4,5
1,1,1,2,2


for example, 1 represents 'grass', 2 represents 'sand', 3 represents 'hill'... and so on.
imshow() works perfectly with my case, but without the legend.

my question is:


  1. Is there a function that can automatically add legend, for example, in my case, I just have to do like this: someFunction('grass','sand',...)

  2. If there isn't, how do I add labels to each value in the matrix. For example, label all the 1 in the matrix 'grass', labell all the 2 in the matrix 'sand'...and so on.



Thank you!

Edit:

Thanks to @dnalow, it's smart really. However, I still wonder if there is any formal solution.

Answer

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]