Matplotlib中的空,零和非零像素表示

时间:2013-10-11 20:16:08

标签: python python-2.7 numpy matplotlib

我正在尝试绘制光线跟踪路径,其中像素值在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()

2 个答案:

答案 0 :(得分:4)

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

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')

Example output

我认为这是一种比手工制作蒙版数组更好的方法,因为让matplotlib为你完成工作,它可以让你独立地明确设置三种不同条件的颜色。

答案 1 :(得分:2)

您可以使用蒙面数组。 http://docs.scipy.org/doc/numpy/reference/generated/numpy.ma.masked_where.html

>>> masked = np.ma.masked_where(M==-1,M)
>>> pl.subplot(111)
>>> pl.imshow(masked, origin='lower', interpolation='nearest')
>>> pl.show()

enter image description here