为 imshow 定义离散颜色图

问题描述 投票:0回答:1

我有一个简单的图像,我在 matplotlib 中使用 imshow 显示它。我想应用自定义颜色图,以便 0-5 之间的值是白色,5-10 之间的值是红色(非常简单的颜色)等。我尝试按照本教程进行操作:

http://assorted-experience.blogspot.com/2007/07/custom-colormaps.html使用以下代码:

cdict = {
'red'  :  ((0., 0., 0.), (0.5, 0.25, 0.25), (1., 1., 1.)),
'green':  ((0., 1., 1.), (0.7, 0.0, 0.5), (1., 1., 1.)),
'blue' :  ((0., 1., 1.), (0.5, 0.0, 0.0), (1., 1., 1.))
}

my_cmap = mpl.colors.LinearSegmentedColormap('my_colormap', cdict, 3)

plt.imshow(num_stars, extent=(min(x), max(x), min(y), max(y)), cmap=my_cmap)
plt.show()

但这最终会显示奇怪的颜色,而我只需要我想要定义的 3-4 种颜色。我该怎么做?

python matplotlib imshow
1个回答
123
投票

您可以使用

ListedColormap
将白色和红色指定为颜色图中唯一的颜色,并且边界确定从一种颜色到下一种颜色的过渡:

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()

生成的图形只有两种颜色:

enter image description here

对于一个有些不同的问题,我提出了本质上相同的事情:Python 中的二维网格数据可视化

该解决方案的灵感来自于 matplotlib 示例。该示例解释了

bounds
必须比使用的颜色数量多 1。

BoundaryNorm
是一种标准化,它将一系列值映射为整数,然后使用整数来分配相应的颜色。
cmap.N
,在上面的示例中,仅定义颜色数量。

© www.soinside.com 2019 - 2024. All rights reserved.