我有一个包含多个区域的 2D 表面,我想将其绘制为不同的颜色,每种颜色代表一个给定的区域。
我遇到的问题是我的颜色条没有均匀地间隔不同的颜色(使用 5 个区域时),或显示正确数量的区域(使用 9 个区域时)。
我的代码基于这个例子:
import matplotlib as mpl
import matplotlib.pyplot as plt
cmap = ListedColormap([str(x) for x in np.linspace(0.0, 1.0, 5)])
# If a ListedColormap is used, the length of the bounds array must be
# one greater than the length of the color list. The bounds must be
# monotonically increasing.
bounds = np.linspace(0.0, 1.0, 6)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
plt.contourf(np.array([[1.0, 1.5, 2.0, 2.5, 3.0], [3.5, 4.0, 4.5, 5.0, 5.0]]), cmap=cmap)
cb2 = plt.colorbar(cmap=cmap, norm=norm)
Run Code Online (Sandbox Code Playgroud)
结果:
我不知道是什么原因造成的,也不知道如何解决。
如果您不指定级别,matplotlib 会自动选择它们。您可以使用关键字级别指定。因此,例如,如果您想要从 1 到 5 均匀间隔的 5 个区域,您可以使用plt.contourf(np.array([[1.0, 1.5, 2.0, 2.5, 3.0], [3.5, 4.0, 4.5, 5.0, 5.0]]), cmap=cmap, levels = np.linspace(1.0, 5.0, 6))