python - 如何使用 "upper"和 "lower"值构建一致的离散颜色图/颜色条

标签 python matplotlib colorbar

一张图片胜过一千个字: https://www.harrisgeospatial.com/docs/html/images/colorbars.png

我想用 matplotlib 获得与右边那个相同的颜色条。 默认行为对“上”/“下”和相邻单元格使用相同的颜色...

感谢您的帮助!

这是我的代码:

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

N = 100
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2

fig, ax = plt.subplots(1, 1, figsize=(8, 8))

# even bounds gives a contour-like effect
bounds = np.linspace(-1, 1, 10)
norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)
pcm = ax.pcolormesh(X, Y, Z,
                    norm=norm,
                    cmap='RdBu_r')
fig.colorbar(pcm, ax=ax, extend='both', orientation='vertical')

最佳答案

为了让颜色图的“上方”/“下方”颜色采用该 map 的第一种/最后一种颜色,但仍与颜色映射范围内的最后一种颜色不同,您可以从颜色图中获得另一种颜色比你在 BoundaryNorm 中有边界,并使用第一种和最后一种颜色作为“over”/“under”颜色的相应颜色。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors

N = 100
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2

fig, ax = plt.subplots(1, 1, figsize=(8, 8))

# even bounds gives a contour-like effect
bounds = np.linspace(-1, 1, 11)
# get one more color than bounds from colormap
colors = plt.get_cmap('RdBu_r')(np.linspace(0,1,len(bounds)+1))
# create colormap without the outmost colors
cmap = mcolors.ListedColormap(colors[1:-1])
# set upper/lower color
cmap.set_over(colors[-1])
cmap.set_under(colors[0])
# create norm from bounds
norm = mcolors.BoundaryNorm(boundaries=bounds, ncolors=len(bounds)-1)
pcm = ax.pcolormesh(X, Y, Z, norm=norm, cmap=cmap)
fig.colorbar(pcm, ax=ax, extend='both', orientation='vertical')

plt.show()

enter image description here

关于python - 如何使用 "upper"和 "lower"值构建一致的离散颜色图/颜色条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56928005/

相关文章:

python - 圆弧补丁之间的填充 - Matplotlib

pandas - 带颜色条的 Pandas DataFrame 绘图上不显示 X 轴标签

python - 解析 askopenfilenames() 的结果?

Python:将频率响应转换为脉冲响应

python - 类型错误 : object of type 'IMapIterator' has no len() for pool. imap

python - 如何使用 python 和 Matplotlib 更新绘图

python - 在一个脚本中设置环境变量并在另一个脚本中使用该变量

python - 如何清除 Python/matplotlib 内存?

matlab - 如何从两种颜色创建内插颜色图或调色板?

python-2.7 - 在 matplotlib 中更改颜色图的字体大小