Pylab色彩映射生成器返回常量查找表

时间:2017-08-18 15:12:33

标签: python matplotlib colormap

我在data['coeff']数组中有以下data列:

[2.57270343, 3.65648059, 2.23084319, 4.80688107, 6.701842, 9.74599594, 7.05068671, 4.01677958, 3.37391547, 3.1511914, 2.38645804, 2.8914971, 3.49830092, 1.44652964, 6.689542, 7.57978187, 10.44210292, 9.96295341, 4.64736146, 3.1432992, 3.57139011, 3.46039262, 3.1436559, 2.56808725, 6.4063686, 7.31260831, 7.26623531, 10.46764653, 6.73590746, 2.7361601, 4.84963666, 5.61582771, 2.86951066, 3.46070112, 5.6345987, 15.91982055, 16.49156807, 11.90533765, 5.11663041, 2.0236397, 9.56519465, 7.69136698, 6.05681034, 4.23944285, 11.4375905, 23.21954318, 25.07053804, 14.68918469, 3.85383511, 2.2003411, 5.09153196, 6.61014214, 10.88575876, 5.09483765, 18.3454972, 27.26258116, 25.72212513, 8.84484278, 1.57545174, 1.8912232, 16.78862314, 20.29314535, 12.44983752, 3.6037403, 3.0240955, 2.30155483, 1.89219047, 5.04316851, 5.45651532, 5.4099686, 6.20357723, 3.29846311, 1.83343417, 5.46524273, 5.9786796, 4.16043566, 5.28458388, 3.69230367, 1.12351996, 3.5924855, 2.18969866, 6.26344489, 6.56806219, 4.03959973]

当我将这些数据传递给pylab.cm.RdBu(data['coeff'])函数时,它会返回一个常量表(每个点都有相同的颜色):

array([[ 0.01960784,  0.18823529,  0.38039216,  1.        ],
       [ 0.01960784,  0.18823529,  0.38039216,  1.        ],
       [ 0.01960784,  0.18823529,  0.38039216,  1.        ],
       ...
       [ 0.01960784,  0.18823529,  0.38039216,  1.        ]])

似乎出现了问题,因为当scattercmap一起使用时,一切正常(即点被正确着色和缩放):

plt.scatter(data['x'], data['y'], c=data['coeff'], cmap='RdBu', marker='o')

1 个答案:

答案 0 :(得分:1)

Matplotlib色图在0和1之间归一化。任何值0 <= x <= 1都会给出色彩图中的颜色。如果将色彩映射应用于值x < 0,则会返回与0对应的值,如果将色彩映射应用于值x > 1,则会返回与{1对应的值1}}。
后一种情况发生在这里。由于列表中的所有值都高于1,因此您将获得与

相同的结果
plt.cm.RdBu(np.ones(len(data)))

将色彩图作为输入的大多数绘图命令将在内部使用标准化将值映射到范围[0,1],然后应用色彩映射。归一化也可以在那些命令中外部给出,例如

plt.scatter(..., c=data, cmap='RdBu', vmin=1.2, vmax=11.5)

norm = plt.Normalize(vmin=1.2, vmax=11.5)
plt.scatter(..., c=data, cmap='RdBu', norm=norm)

直接将颜色映射应用于数据因此也需要使用规范化。

norm = plt.Normalize(vmin=data.min(), vmax=data.max())
plt.cm.RdBu(norm(data))