<p>为了使colormap的“over”/“under”颜色取该贴图的第一个/最后一个颜色,但仍与colormappaged范围内的最后一个颜色不同,您可以从colormap中获得比<code>BoundaryNorm</code>中的边界多的一个颜色,并将第一个和最后一个颜色用作“over”/“under”颜色的各自颜色。在</p>
<pre><code>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()
</code></pre>
<p><a href="https://i.stack.imgur.com/YMcly.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YMcly.png" alt="enter image description here"/></a></p>