中心峰值和边缘为零的 Matplotlib 颜色图

Matpliblib colormap with peak at center and zero at edges

我正在寻找突出显示中心(值为 1)并且边缘只有白色(值为 0 和 2)的自定义颜色图。理想情况下应该有从 1 到 [0, 2] 的梯度。

通常的颜色图恰恰相反:从中心发散(中心为白色)。

感谢您的帮助

您可以基于 matplotlib 的可用颜色图创建。

from matplotlib.colors import ListedColormap

def show_cmap(ax, cmap):
    n = 256
    ax.imshow(np.tile(np.arange(n), [int(n*0.20),1]),
              cmap=cmap,
              interpolation="nearest", aspect="auto")
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    

c1 = plt.cm.Blues(range(0, 128))
c2 = c1[::-1]
c = np.vstack([c1, c2])
cmap = ListedColormap(c)

fig, ax = plt.subplots(1, 1, figsize=(7.2, 7.2))
show_cmap(ax, cmap)

您可以使用 matplotlib.colors 模块中的 from_list method from LinearSegmentedColormap

在这里,我们给出 3 种颜色作为列表 (["white", "red", "white"])。这可以通过更改任何颜色名称轻松自定义。

例如:

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

cmap = LinearSegmentedColormap.from_list('wrw', ["white", "red", "white"], N=256)

a = np.arange(0, 2, 0.01).reshape(20, 10)
fig, ax = plt.subplots()

p = ax.pcolormesh(a, cmap=cmap, vmin=0, vmax=2)

fig.colorbar(p)

plt.show()