问题
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.
I know there is a colormap called "RdYlGr", which goes from red-yellow-green. Maybe it's possible to use this map? But how?
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").
回答1:
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
来源:https://stackoverflow.com/questions/27206300/assign-color-to-value