如何在matplotlib中将图例添加到imshow() [英] How to add legend to imshow() in matplotlib
问题描述
我正在使用matplotlib
在plot()
或bar()
中,如果我们向其添加标签,则可以轻松放置图例.但是如果是contourf()
或imshow()
我知道有一个colorbar()
可以显示颜色范围,但是不满意.我想要一个带有名称(标签)的图例.
我能想到的是,在矩阵中的每个元素上添加标签,然后尝试legend()来查看其是否有效,但是如何在标签上像值一样添加标签? >
在我的情况下,原始数据如下:
1,2,3,3,4
2,3,4,4,5
1,1,1,2,2
例如,1代表草",2代表沙",3代表山" ...依此类推. imshow()非常适合我的情况,但没有图例.
我的问题是:
-
是否有一个可以自动添加图例的函数,例如,就我而言,我只需要这样做:someFunction('grass','sand',...)
-
如果没有,如何将标签添加到矩阵中的每个值.例如,将矩阵1中的所有1标记为草",将矩阵2中的所有2标记为沙" ...等等.
谢谢!
修改:
感谢@dnalow,它确实很聪明.但是,我仍然想知道是否有任何正式的解决方案.
我想您必须伪造您的图例,因为创建图例需要一行代码.
您可以执行以下操作:
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()
当然,这还不是很令人满意.但是也许您可以在此基础上构建一些东西.
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).
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:
Is there a function that can automatically add legend, for example, in my case, I just have to do like this: someFunction('grass','sand',...)
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.
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]
这篇关于如何在matplotlib中将图例添加到imshow()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!