您可以使用cmap.N将白色和红色指定为颜色图中的唯一颜色,并且边界确定从一种颜色到另一种颜色的过渡位置:
import matplotlib.pyplot as plt
from matplotlib import colors
import numpy as np
np.random.seed(101)
zvals = np.random.rand(100, 100) * 10
# make a color map of fixed colors
cmap = colors.ListedColormap(['white', 'red'])
bounds=[0,5,10]
norm = colors.BoundaryNorm(bounds, cmap.N)
# tell imshow about color map so that only set colors are used
img = plt.imshow(zvals, interpolation='nearest', origin='lower',
cmap=cmap, norm=norm)
# make a color bar
plt.colorbar(img, cmap=cmap, norm=norm, boundaries=bounds, ticks=[0, 5, 10])
plt.savefig('redwhite.png')
plt.show()
结果图形只有两种颜色:
我为一个稍有不同的问题提出了相同的建议:Python中的2D网格数据可视化
该解决方案受到matplotlib示例的启发。 该示例说明cmap.N必须比使用的颜色数多一。
cmap.N是一种规范化,可将一系列值映射为整数,然后将其用于分配相应的颜色。 在上面的示例中,cmap.N仅定义了颜色的数量。