在 matplotlib 中为 imshow 定义离散颜色图 [英] Defining a discrete colormap for imshow in matplotlib
问题描述
我有一个简单的图像,我在 matplotlib 中用 imshow 显示.我想应用自定义颜色图,以便 0-5 之间的值是白色,5-10 是红色(非常简单的颜色)等.我尝试按照本教程进行操作:
该解决方案的灵感来自 matplotlib 示例.该示例说明 bounds
必须比使用的颜色数多 1.
BoundaryNorm
是将一系列值映射到整数的归一化,然后用于分配相应的颜色.cmap.N
,在上面的例子中,只是定义了颜色的数量.
I have a simple image that I'm showing with imshow in matplotlib. I'd like to apply a custom colormap so that values between 0-5 are white, 5-10 are red (very simple colors), etc. I've tried following this tutorial:
http://assorted-experience.blogspot.com/2007/07/custom-colormaps.html with the following code:
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()
But this ends up showing strange colors, and I only need 3-4 colors that I want to define. How do I do this?
You can use a ListedColormap
to specify the white and red as the only colors in the color map, and the bounds determine where the transition is from one color to the next:
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()
The resulting figure has only two colors:
I proposed essentially the same thing for a somewhat different question: 2D grid data visualization in Python
The solution is inspired by a matplotlib example. The example explains that the bounds
must be one more than the number of colors used.
The BoundaryNorm
is a normalization that maps a series of values to integers, which are then used to assign the corresponding colors. cmap.N
, in the example above, just defines the number of colors.
这篇关于在 matplotlib 中为 imshow 定义离散颜色图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!