Matplotlib:将渐变色图与列出的色图结合起来

时间:2019-08-14 11:27:17

标签: python matplotlib

通过计算,我有一个DataFrame的值为(0,1)(请注意,两个数字都不包括在内)。

然后,我用0填充了一些缺失值。

我要为热图创建以下颜色图:

  1. 如果数据丢失(== 0):热图中的白色(仅一种白色)。
  2. 如果数据低于阈值(例如0
  3. 如果数据高于阈值:红色(或其他任何无关紧要的)渐变色图。

这里的关键是我希望1和2具有精确的灰色和白色。我不希望在阈值以下的值和阈值以上的值之间出现任何梯度。

我已经看到了有关合并两个色图的问题:Combining two matplotlib colormaps,但我真的不明白该代码在哪个代码中将负值映射到不同的色图,或者如何使第二个色图变为非渐变。

仅用于示例目的的数据:

data = np.random.rand(10,10) * 2 - 1.3
data[data < 0] = 0

还有ListedColormap

cmap = colors.ListedColormap(['gray', 'white', 'red'])
bounds = [0, 0.0001, 0.1, 1.0]
norm = colors.BoundaryNorm(bounds, cmap.N)

plt.pcolor(data, cmap=cmap)
plt.colorbar()
plt.show()

它给了我什么:

example_heatmap

再次:我希望将热图的红色部分更改为渐变(并且理想情况下,颜色栏不应具有与现在相同大小的所有颜色)。

谢谢。

更新

我终于意识到,可以使用通过cdict定义的一种颜色映射来制作图像,就像对此的回答:Create own colormap using matplotlib and plot color scale

但是,我根本达不到我的期望。

我有这个cdict

cdict = {'red':   ((0.0,  1.0, 1.0),
                   (0.0001,  1.0, 1.0),
                   (lower_bound, 0.99, 0.99),
                   (threshold, 0.99, 0.99),
                   (threshold + 0.0001, 0.98, 0.98),
                   (upper_bound,  0.57, 0.57),
                   (upper_bound + 0.0001,  0.0, 0.0),
                   (1.0, 0.0, 0.0)),

         'green': ((0.0,  1.0, 1.0),
                   (0.0001, 1.0, 1.0),
                   (lower_bound, 0.92, 0.92),
                   (threshold, 0.92, 0.92),
                   (threshold + 0.0001, 0.63, 0.63),
                   (upper_bound,  0.0, 0.0),
                   (upper_bound + 0.0001,  0.0, 0.0),
                   (1.0, 0.0, 0.0)),

         'blue':  ((0.0,  1.0, 1.0),
                   (0.0001,  1.0, 1.0),
                   (lower_bound, 0.82, 0.82),
                   (threshold, 0.82, 0.82),
                   (threshold + 0.0001, 0.42, 0.42),
                   (upper_bound, 0.0, 0.0),
                   (upper_bound + 0.0001,  0.0, 0.0),
                   (1.0, 0.0, 0.0))
        }
cmap = LinearSegmentedColormap('cdict', cdict)

界限:

lower_bound = data[data != 0].min()
upped_bound = data.max()
threshold = 0.2

对我来说(lower_bound, upper_bound, threshold) = (0.02249988938707692, 0.6575927961263812, 0.2)

图:

fig, ax = plt.subplots(figsize = (15, 6))
im = ax.imshow(data, cmap = cmap)
cbar = ax.figure.colorbar(im, ax = ax)

但是,我得到了:

second_try

怎么可能?如果根据我对cdict的理解,黑色仅分配给高于upper_bound的值,为什么我却有那么多黑色正方形,这没有意义,因为upper_bound的最大值是所有数组...

1 个答案:

答案 0 :(得分:0)

您希望白色从0到阈值,并且从阈值到1渐变。当数据也位于0到1之间时,这非常容易。可以通过// api.js class Api { constructor() { this.worker = new Worker('worker.js'); } doCalculation(input) { this.worker.postMessage({input: input}); return new Promise((resolve => { this.worker.addEventListener('message', (e) => { resolve(e.data); }); })) } } 设置小于0的值的颜色。

.set_under

enter image description here