matplotlib colorbar 以不同的颜色扩展

matplotlib colorbar extend in different color

我在二维矩阵中有数据,我想 plt.colorbar(extend = "both"),我已将我的数据设置为最大 100 并在 -100 开采,现在我想看看在哪里我的数据超过 100(这是一个饱和区域)所以颜色条的范围必须与颜色条的颜色不同有没有办法设置一个 cmap 的提示颜色不同?喜欢<"yellow"|"seismic"|"orange">

您可以使用 .set_over('orange') and .set_under('yellow') on the colormap. If you're using a standard colormap, you should first make a copy to prevent that the original colormap gets changed. .set_extremes(over=..., under=..., bad=...) 一次性更改这些颜色。 (bad 用于无效值,例如 np.nannp.infbad 默认为完全透明。

这是一个例子:

import matplotlib.pyplot as plt
import numpy as np

xmin, xmax = 0, 10
ymin, ymax = 0, 7

z = np.random.randint(-150, 150, size=(ymax, xmax))

cmap = plt.get_cmap('seismic').copy()
cmap.set_extremes(under='yellow', over='orange')
norm = plt.Normalize(-100, 100)
plt.imshow(z, cmap=cmap, norm=norm, extent=[xmin, xmax, ymin, ymax], aspect='auto')
plt.colorbar(extend='both')
plt.show()

在为注释选择白色或黑色时,Seaborn 的热图会考虑这些颜色。

import seaborn as sns

sns.heatmap(z, annot=True, fmt='d', cmap=cmap, norm=norm, cbar_kws={'extend': 'both'})