Python 颜色映射,但所有零值都映射到黑色 [英] Python color map but with all zero values mapped to black
问题描述
我有一个对应于格点的元素的方形阵列.一些元素为零,其余元素在 1 到 2700 之间变化.使用 imshow 和 OrRd 颜色图,我希望所有大于 0 的点阵站点都显示相应的颜色,但重要的是,所有值为 0 的站点都是显示为黑色.我尝试定义一个新的颜色映射如下:
I have a square array of elements which correspond to lattice sites. Some of the elements are zero and the rest vary between 1 and about 2700. Using imshow and the OrRd colour map, I want all lattice sites greater than 0 to display the corresponding colour but importantly, all sites with value 0 to be displayed as black. I have tried defining a new color map as follows:
colors = [(0,0,0)] + [(pylab.cm.OrRd(i)) for i in range(1,256)]
new_map = matplotlib.colors.LinearSegmentedColormap.from_list('new_map', colors, N=256)
但是我的数组中的值范围太大,因此很多非零值显示为黑色.
but the range of values in my array is too large and so a lot of non-zero values get displayed as black.
非常感谢.
推荐答案
Matplotlib 的颜色图有一个 set_bad
和 set_under
属性,可用于此目的.这个例子展示了如何使用 set_bad
The colormaps of Matplotlib have a set_bad
and set_under
property which can be used for this. This example shows how to use the set_bad
import matplotlib.pyplot as plt
import numpy as np
# make some data
a = np.random.randn(10,10)
# mask some 'bad' data, in your case you would have: data == 0
a = np.ma.masked_where(a < 0.05, a)
# cmap = plt.cm.OrRd
# for mpl 3.3 and higher use
cmap = mpl.cm.get_cmap("OrRd").copy()
cmap.set_bad(color='black')
im = plt.imshow(a, interpolation='none', cmap=cmap)
要使用 set_under
变体,您必须将 vmin
关键字添加到绘图命令中,并且设置略高于零(但低于任何其他有效值):>
To use the set_under
variant you have to add the vmin
keyword to the plotting command and setting is slightly above zero (but below any other valid value):
cmap.set_under(color='black')
im = plt.imshow(a, interpolation='none', cmap=cmap, vmin=0.0000001)
这篇关于Python 颜色映射,但所有零值都映射到黑色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!