Python 如何使用 matplotlib 的颜色图将数字映射到颜色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15140072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to map number to color using matplotlib's colormap?
提问by Psirus
Consider a variable xcontaining a floating point number. I want to use matplotlib's colormaps to map this number to a color, but not plot anything. Basically, I want to be able to choose the colormap with mpl.cm.autumnfor example, use mpl.colors.Normalize(vmin = -20, vmax = 10)to set the range, and then map xto the corresponding color. But I really don't get the documentation of mpl.cm, so if anyone could give me a hint.
考虑一个x包含浮点数的变量。我想使用 matplotlib 的颜色图将此数字映射到颜色,但不绘制任何内容。基本上,我希望能够选择颜色图,mpl.cm.autumn例如mpl.colors.Normalize(vmin = -20, vmax = 10)用于设置范围,然后映射x到相应的颜色。但我真的没有得到 的文档mpl.cm,所以如果有人能给我一个提示。
采纳答案by David Zwicker
It's as simple as cm.hot(0.3), which returns (0.82400814813704837, 0.0, 0.0, 1.0).
它就像 一样简单cm.hot(0.3),它返回(0.82400814813704837, 0.0, 0.0, 1.0)。
A full working program could read
一个完整的工作程序可以阅读
import matplotlib.cm as cm
print(cm.hot(0.3))
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))
回答by ImportanceOfBeingErnest
You can get a color from a colormap by supplying an argument between 0 and 1, e.g. cm.autumn(0.5).
您可以通过提供 0 和 1 之间的参数从颜色图中获取颜色,例如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))

