在matplotlib中为imshow定义离散色彩图 [英] Defining a discrete colormap for imshow in matplotlib

查看:140
本文介绍了在matplotlib中为imshow定义离散色彩图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 和以下代码:

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种颜色即可.我该怎么做?

But this ends up showing strange colors, and I only need 3-4 colors that I want to define. How do I do this?

推荐答案

您可以使用ListedColormap将白色和红色指定为颜色图中的唯一颜色,并且边界确定从一种颜色过渡的位置到下一个:

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:

对于一个稍微不同的问题,我提出了基本相同的建议: Python中的2D网格数据可视化

I proposed essentially the same thing for a somewhat different question: 2D grid data visualization in Python

该解决方案的灵感来自 matplotlib示例.该示例说明bounds必须比使用的颜色数多一.

The solution is inspired by a matplotlib example. The example explains that the bounds must be one more than the number of colors used.

BoundaryNorm 是映射一个系列值转换为整数,然后用于分配相应的颜色.在上面的示例中,cmap.N仅定义颜色的数量.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆