但所有零值都映射为黑色

但所有零值都映射为黑色

本文介绍了Python颜色映射,但所有零值都映射为黑色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我有一个与晶格位置相对应的元素方阵.其中一些元素为零,其余元素在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_badset_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
cmap.set_bad(color='black')

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')
plt.imshow(a, interpolation='none', cmap=cmap, vmin=0.0000001)

这篇关于Python颜色映射,但所有零值都映射为黑色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 15:09