简体   繁体   English

在matplotlib中为imshow定义离散色图

[英]Defining a discrete colormap for imshow in matplotlib

I have a simple image that I'm showing with imshow in matplotlib. 我有一个简单的图像,我在matplotlib中使用imshow显示。 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: 我想应用自定义色图,使0-5之间的值为白色,5-10为红色(非常简单的颜色)等。我尝试过本教程:

http://assorted-experience.blogspot.com/2007/07/custom-colormaps.html with the following code: 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()

But this ends up showing strange colors, and I only need 3-4 colors that I want to define. 但这最终显示出奇怪的颜色,我只需要3-4种我想要定义的颜色。 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: 您可以使用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()

The resulting figure has only two colors: 结果图只有两种颜色:

在此输入图像描述

I proposed essentially the same thing for a somewhat different question: 2D grid data visualization in Python 对于一个稍微不同的问题我提出了基本相同的东西: Python中的2D网格数据可视化

The solution is inspired by a matplotlib example . 该解决方案的灵感来自matplotlib示例 The example explains that the bounds must be one more than the number of colors used. 该示例解释了bounds必须比使用的颜色数多一个。

The BoundaryNorm is a normalization that maps a series of values to integers, which are then used to assign the corresponding colors. BoundaryNorm是一个规范化,它将一系列值映射到整数,然后用于分配相应的颜色。 cmap.N , in the example above, just defines the number of colors. cmap.N ,在上面的例子中,只定义了颜色的数量。

for why LinearSegmentedColormap shows strange color, I think this link would be helpful. 为什么LinearSegmentedColormap显示奇怪的颜色,我认为这个链接会有所帮助。

http://matplotlib.org/examples/pylab_examples/custom_cmap.html http://matplotlib.org/examples/pylab_examples/custom_cmap.html

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

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