如何从matplotlib中的简单数组生成colormap数组

2024-05-20 20:46:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: thetofromimportdata参数matplotlibcm
1条回答
网友
1楼 · 发布于 2024-05-20 20:46:18

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

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

相关问题 更多 >