如何在 matplotlib 中向 im​​show() 添加图例 [英] How to add legend to imshow() in matplotlib

查看:35
本文介绍了如何在 matplotlib 中向 im​​show() 添加图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 matplotlib

plot()bar() 中,如果我们给它们添加标签,我们可以很容易地放置图例.但如果它是 contourf()imshow()

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

我知道有一个colorbar()可以呈现颜色范围,但是不满意.我想要这样一个有名字(标签)的传说.

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).

我能想到的是,给矩阵中的每个元素添加标签,然后,尝试legend(),看看它是否有效,但是如何给元素添加标签,比如一个值??

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

例如,1 代表草",2 代表沙",3 代表山"……以此类推.imshow() 非常适合我的情况,但没有图例.

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

我的问题是:

  1. 有没有可以自动添加图例的函数,比如我的情况,我只需要这样:someFunction('grass','sand',...)

  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',...)

如果没有,如何为矩阵中的每个值添加标签.例如,将矩阵草"中的所有 1 标记,将矩阵沙"中的所有 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.

谢谢!

编辑:

感谢@dnalow,它真的很聪明.但是,我仍然想知道是否有任何正式的解决方案.

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.

你可以这样做:

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.

这篇关于如何在 matplotlib 中向 im​​show() 添加图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆