如何构建一个具有“上”和“下”值的一致的离散colormap/colorbar

2024-05-20 19:23:30 发布

您现在位置:Python中文网/ 问答频道 /正文

一个形象胜过千言万语: 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')

Tags: importnormmatplotlib颜色asnpfigplt
2条回答

为了使colormap的“over”/“under”颜色取该贴图的第一个/最后一个颜色,但仍与colormappaged范围内的最后一个颜色不同,您可以从colormap中获得比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

正如我在评论中建议的那样,你可以用

pcm = ax.pcolormesh(X, Y, Z, norm=norm, cmap='rainbow_r')

这就产生了:

enter image description here

您可以定义自己的颜色映射,如下所示:Create own colormap using matplotlib and plot color scale

相关问题 更多 >