其他分享
首页 > 其他分享> > 如何使用“上”和“下”值构建一致的离散色图/颜色条

如何使用“上”和“下”值构建一致的离散色图/颜色条

作者:互联网

一张图片胜过千言万语:
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')

解决方法:

为了使色彩图的“上方”/“下方” – 颜色采用该地图的第一种/最后一种颜色,但仍然与色彩映射范围内的最后一种颜色不同,您可以从色彩图中获得一种颜色,而不是BoundaryNorm中的边界,并使用第一个和最后一个颜色作为“over”/“under”-color的相应颜色.

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

标签:colorbar,python,matplotlib
来源: https://codeday.me/bug/20191003/1850325.html