繁体   English   中英

如何在Matplotlib Contourf和Colorbar中显示给定数量的颜色

[英]How to display a given number of colors in a matplotlib contourf and colorbar

我有一个带有多个区域的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)

结果:

五个级别,请注意颜色栏中的间距不均匀

九个级别,请注意,颜色栏中有八个级别(最低的两个级别略有不同

我不知道是什么原因导致的,或者如何解决。

如果您未指定级别,则matplotlib会自动选择它们。 您可以使用关键字级别进行指定。 因此,例如,如果您希望5个区域从1到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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM