如何从 matplotlib 中的简单数组生成颜色图数组

How can I generate a colormap array from a simple array in matplotlib

matplotlib的一些函数中,我们必须传递一个color参数而不是cmap参数,比如bar3d.

所以我们必须手动生成一个Colormap。如果我有一个像这样的 dz 数组:

dz = [1,2,3,4,5]

我想要的是:

ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=cm.jet(dz), zsort='average')

然而,它不起作用,似乎Colormap实例只能转换规范化数组。

>>> 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.        ]])

当然,这不是我想要的

我必须这样做:

>>> 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's document中说:

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)

这是我正在使用的导入

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm

您问题的答案在您复制到问题中的文档片段中给出:

...from the interval [0, 1] to the RGBA color...

但是如果您发现您的代码丑陋,您可以尝试让它变得更好:

  1. 您不必手动指定规范化的限制(如果您打算使用 min/max):

    norm = plt.Normalize()
    colors = plt.cm.jet(norm(dz))
    
  2. 如果你觉得丑陋(虽然我不明白为什么),你可以继续手动完成):

    colors = plt.cm.jet(np.linspace(0,1,len(dz)))
    

    然而,这个解决方案仅限于等距颜色(给定示例中的 dz,这是您想要的。

  3. 然后你也可以复制Normalize的功能(因为你似乎不喜欢它):

    lower = dz.min()
    upper = dz.max()
    colors = plt.cm.jet((dz-lower)/(upper-lower))
    
  4. 使用辅助函数:

    def get_colors(inp, colormap, vmin=None, vmax=None):
        norm = plt.Normalize(vmin, vmax)
        return colormap(norm(inp))
    

    现在你可以这样使用了:

    colors = get_colors(dz, plt.cm.jet)