Matplotlib:结合渐变色贴图和列出的颜色贴图

2024-03-29 05:14:29 发布

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

我有一个数据帧,它的值来自(0,1)(注意这两个数字不包括在内)。在

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

要为以下热图创建颜色贴图I:

  1. 如果数据丢失(=0):热图中的白色(只有一种白色)。在
  2. 如果数据低于阈值(例如0<;data<;0.5):浅色(仅一种浅色)。在
  3. 如果数据高于阈值:红色(或任何其他颜色,不重要)颜色的渐变颜色贴图。在

这里的关键是我想有一个精确的灰色和白色。和2。我不希望在低于阈值的值和高于阈值的值之间有任何渐变。在

我已经看到了组合两个颜色映射的问题:Combining two matplotlib colormaps,但我不真正理解在该代码中,它在哪里将负值映射到不同的colormap,或者如何使第二个colormap非渐变。在

数据仅供示例:

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

ListedColormap

^{pr2}$

它带给我的是:

example_heatmap

再一次:我想把热图的红色部分改成一个渐变(并且,理想情况下,colorbar不应该有与现在一样大小的所有颜色)。在

谢谢。在

更新:

我终于意识到,通过cdict定义的一个colormap是可能的,作为对这个问题的回答: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是所有数组的最大值。。。在


Tags: 数据ltdatathreshold颜色阈值axupper
1条回答
网友
1楼 · 发布于 2024-03-29 05:14:29

您需要从0到阈值的白色,以及从阈值到1的渐变。当您的数据也在0和1之间时,这很简单。0以下值的颜色可以通过.set_under设置。在

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap


data = np.random.rand(10,10) * 2 - 1.3

thresh = 0.2
nodes = [0,thresh, thresh, 1.0]
colors = ["white", "white", "red", "indigo"]
cmap = LinearSegmentedColormap.from_list("", list(zip(nodes, colors)))
cmap.set_under("gray")

fig, ax = plt.subplots()
im = ax.imshow(data, cmap=cmap, vmin=0, vmax=1)
fig.colorbar(im, extend="min")
plt.show()

enter image description here

相关问题 更多 >