为值分配颜色 [英] Assign color to value

查看:67
本文介绍了为值分配颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用matplotlib或colormap为值赋值颜色.更具体地讲:如果我有一个较小的值(假设-14是最小的值)和一个较高的值(例如86是最大的值),那么我想将具有较低值的对象打印为红色,值较高的对象会变绿(-14->完全红色; 86->完全绿色).对于值介于-14和86之间的对象,我想为它们分配红色和绿色之间的颜色.

I'd like to assign to values colors, using matplotlib or colormap. More concretely: If I've got a small value (let's say that -14 is the smallest value) and a high value (let's say 86 is the highest value), I'd like to print the objects with low values more red, and objects which have higher values greener (-14 --> completely red ; 86 --> completely green). For objects with values between -14 and 86, I'd like to assign to them colors between red and green.

我知道有一个名为"RdYlGr"的色图,它从红黄绿开始.也许可以使用这张地图?但是如何?

I know there is a colormap called "RdYlGr", which goes from red-yellow-green. Maybe it's possible to use this map? But how?

总结:如何使用maplotlib的颜色图将浮点数(例如,范围从-14到86的6.2)映射到相应的十六进制颜色字符串( eg ,#A0CBE2").

In summary: how can I use maplotlib's colormaps to map a floating point number (eg, 6.2 from the range -14 to 86) to a corresponding hex color string (eg, "#A0CBE2").

推荐答案

您可以直接使用colormaps进行大多数操作,但是matplotlib给出rgb而不是十六进制值,因此您需要自己执行十六进制.这是一个示例:

You can do most of this directly with colormaps, but matplotlib give the rgb and not hex values, so you need to do the hex on your own. Here's an example:

import matplotlib.cm as cm
import matplotlib.colors as colors

norm = colors.Normalize(vmin=-14, vmax=86)
f2rgb = cm.ScalarMappable(norm=norm, cmap=cm.get_cmap('RdYlGn'))

def f2hex(f2rgb, f):
    rgb = f2rgb.to_rgba(f)[:3]
    return '#%02x%02x%02x' % tuple([255*fc for fc in rgb])

print f2hex(f2rgb, -13.5)  #   gives #a60126  ie, dark red
print f2hex(f2rgb, 85.5)   #   gives #016937  ie, dark green with some blue

这篇关于为值分配颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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