如何从Matplotlib中的简单数组生成颜色图数组
在matplotlib
的某些函数中,我们必须传递color
参数而不是cmap
参数,例如bar3d
.
In some functions of matplotlib
, we have to pass an color
argument instead of a cmap
argument, like bar3d
.
因此,我们必须手动生成Colormap
.如果我有这样的dz
数组:
So we have to generate a Colormap
manually. If I have a dz
array like this:
dz = [1,2,3,4,5]
我想要的是:
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=cm.jet(dz), zsort='average')
但是,它不起作用,看来Colormap
实例只能转换规范化的数组.
However, It does not work, it seems Colormap
instances can only convert normalized arrays.
>>> dz = [1,2,3,4,5]
>>> cm.jet(dz)
array([[ 0. , 0. , 0.51782531, 1. ],
[ 0. , 0. , 0.53565062, 1. ],
[ 0. , 0. , 0.55347594, 1. ],
[ 0. , 0. , 0.57130125, 1. ],
[ 0. , 0. , 0.58912656, 1. ]])
当然,这不是我想要的.
Of course, this is not what I want.
我必须做这样的事情:
>>> cm.jet(plt.Normalize(min(dz),max(dz))(dz))
array([[ 0. , 0. , 0.5 , 1. ],
[ 0. , 0.50392157, 1. , 1. ],
[ 0.49019608, 1. , 0.47754586, 1. ],
[ 1. , 0.58169935, 0. , 1. ],
[ 0.5 , 0. , 0. , 1. ]])
代码多么丑陋!
在 matplotlib的文档中说:
通常,Colormap实例用于转换数据值(浮点数) 从间隔[0,1]到相应的RGBA颜色 色彩图代表.有关将数据缩放到[0,1]间隔的信息,请参见 matplotlib.colors.Normalize.值得一提的是 matplotlib.cm.ScalarMappable子类大量使用了此方法 data-> normalize-> map-to-color处理链.
Typically Colormap instances are used to convert data values (floats) from the interval [0, 1] to the RGBA color that the respective Colormap represents. For scaling of data into the [0, 1] interval see matplotlib.colors.Normalize. It is worth noting that matplotlib.cm.ScalarMappable subclasses make heavy use of this data->normalize->map-to-color processing chain.
那为什么我不能只使用cm.jet(dz)
?
So why I can't use just cm.jet(dz)
?
这是我正在使用的导入
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
问题的答案在您复制到问题中的文档的摘要中给出:
The answer to your question is given in the snipplet of the documentation that you copied into your question:
...从间隔[0,1]到RGBA颜色...
...from the interval [0, 1] to the RGBA color...
但是,如果您发现代码丑陋,则可以尝试使其更好:
But if you find your code ugly you could try to make it nicer:
-
您不必手动指定标准化的限制(如果您打算使用最小/最大):
You don't have to specify the limits to the normalization manually (iff you intent to use min/max):
norm = plt.Normalize()
colors = plt.cm.jet(norm(dz))
如果您发现丑陋(不过,我不明白为什么),您可以继续手动进行操作:
If you find that ugly (I don't understand why, though), you could go on and do it manually):
colors = plt.cm.jet(np.linspace(0,1,len(dz)))
但是,这种解决方案仅限于等距的颜色(这是您在示例中给出的dz
想要的颜色.)
However this is solution is limited to equally spaced colors (which is what you want given the dz
in your example.
然后您还可以复制Normalize
的功能(因为您似乎不喜欢它):
And then you can also replicate the functionality of Normalize
(since you seem to not like it):
lower = dz.min()
upper = dz.max()
colors = plt.cm.jet((dz-lower)/(upper-lower))
使用助手功能:
Use a helper function:
def get_colors(inp, colormap, vmin=None, vmax=None):
norm = plt.Normalize(vmin, vmax)
return colormap(norm(inp))
现在您可以像这样使用它:
Now you can use it like this:
colors = get_colors(dz, plt.cm.jet)