我试图绘制光线跟踪路径,其中像素值在matplotlib中变为非“ -1”值。换句话说,我有下面的2D数组代表4条光线路径。光线交叉的每个像素具有随机值。除这些相交的像素外,其余均为“ -1”。我想以白色或不可见(不存在)显示值“ -1”。这怎么可能?

import numpy as np
import scipy as sp
import pylab as pl

M = np.array([[ 0. , -1., -1., -1., -1., -1.],
          [ 0.25, -1.,-1.,-1.,-1.,-1.],
          [ 0.25, -1., -1., -1.,-1.,-1.],
          [ 0.22, -1., -1., -1., -1.,-1.],
          [ 0.16, -1., -1., -1., -1.,-1.],
          [ 0.16, -1., -1., -1., -1.,-1.],
          [ 0.13, -1., -1., -1., -1.,-1.],
          [ 0.10, -1., -1., -1., -1.,-1.],
          [-1., 0.06, 0.14, 0.087, 0.079,0.],
          [ 0., 0.16, 0.10, 0.15, 0.16, 0.],
          [-1., -1., 0., 0.004,-1., -1.]])

pl.subplot(111)
pl.imshow(M, origin='lower', interpolation='nearest')
pl.show()

最佳答案

另一种方法是使用颜色映射(doc)set_underset_overset_bad属性

from copy import copy

# normalize data between vmin and vmax
my_norm = matplotlib.colors.Normalize(vmin=.25, vmax=.75, clip=False)
# clip=False is important, if clip=True, then the normalize function
# clips out of range values to 0 or 1 which defeats what we want to do here.

my_cmap = copy(cm.get_cmap('gray')) # make a copy so we don't mess up system copy
my_cmap.set_under('r', alpha=.5) # make locations over vmax translucent red
my_cmap.set_over('w', alpha=0)   # make location under vmin transparent white
my_cmap.set_bad('g')             # make location with invalid data green

test_data = np.random.rand(10, 10) # some random data between [0, 1]
test_data[5, 5] = np.nan           # add one NaN
# plot!
imshow(test_data, norm=my_norm, cmap=my_cmap, interpolation='nearest')




我认为这是一种比手工制作遮罩阵列更好的方法,因为您让matplotlib为您完成工作,并且可以让您分别显式设置三种不同条件的颜色。

关于python - Matplotlib中的空,零和非零像素表示,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19326526/

10-16 05:18