如何使用 matplotlib 的颜色图将数字映射到颜色?

考虑一个包含浮点数的变量 x。我想使用 matplotlib 的颜色图将这个数字映射到一个颜色,但不绘制任何图形。基本上,我希望能够选择与 mpl.cm.autumn的颜色映射,例如,使用 mpl.colors.Normalize(vmin = -20, vmax = 10)设置范围,然后映射 x到相应的颜色。但我真的没有得到 mpl.cm的文档,所以如果有人可以给我一个提示。

87353 次浏览

It's as simple as cm.hot(0.3):

import matplotlib.cm as cm
    

print(cm.hot(0.3))
(0.8240081481370484, 0.0, 0.0, 1.0)

If you also want to have the normalizer, use

import matplotlib as mpl
import matplotlib.cm as cm
   

norm = mpl.colors.Normalize(vmin=-20, vmax=10)
cmap = cm.hot
x = 0.3


m = cm.ScalarMappable(norm=norm, cmap=cmap)
print(m.to_rgba(x))
(1.0, 0.8225486412996345, 0.0, 1.0)

You can get a color from a colormap by supplying an argument between 0 and 1, e.g. cm.autumn(0.5).

If there is a normalization instance in the game, use the return of the Normalization instead:

import matplotlib.cm as cm
from matplotlib.colors import Normalize


cmap = cm.autumn
norm = Normalize(vmin=-20, vmax=10)
print cmap(norm(5))

Number value to colormap color

import matplotlib.cm as cm
import matplotlib as matplotlib


def color_map_color(value, cmap_name='Wistia', vmin=0, vmax=1):
# norm = plt.Normalize(vmin, vmax)
norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)
cmap = cm.get_cmap(cmap_name)  # PiYG
rgb = cmap(norm(abs(value)))[:3]  # will return rgba, we take only first 3 so we get rgb
color = matplotlib.colors.rgb2hex(rgb)
return color