为 matplotlib tricontourf 设置掩码
Set mask for matplotlib tricontourf
我有一些 numpy 数组,其中包含我将在二维网格上可视化的数据。有些数据是非物理的,我想屏蔽这些数据。但是,我不知道如何正确设置 tricontour
的掩码属性。我试过了:
import matplotlib.pyplot as mp
import numpy as np
with open('some_data.dat', 'r') as infile:
x, y, z = np.loadtxt(infile, usecols=(0, 1, 2), unpack=True)
isbad = np.less(z, 1.4) | np.greater(z, 2.1)
mp.tricontourf(x, y, z, mask = isbad)
但是结果图根本就没有被屏蔽。我尝试了 masking part of a contourf plot in matplotlib,即
z2 = np.ma.array(z, mask= isbad)
mp.tricontourf(x, y, z2)
这也没有用。我想使用 tricontourf
instrad of contourf
,因为我不想对我的数据进行网格化。
z[isbad] = np.nan
调用 tricontourf 时导致分段错误
这是图,红色是我想标记为非物理的。
技巧来了。我需要收集三角形的索引(它们是 z 的索引!),评估它们是否好,然后只接受至少一个角有效的三角形(将维度从 (ntri, 3) 减少到 ntri
triang = tr.Triangulation(x, y)
mask = np.all(np.where(isbad[triang.triangles], True, False), axis=1)
triang.set_mask(mask)
colplt = mp.tricontourf(triang, z)
mp.colorbar()
受此启发link:http://matplotlib.org/examples/pylab_examples/tripcolor_demo.html
wsj 的回答对我不起作用,因为它没有删除某些屏蔽点(我认为不是所有节点都不好)。
This solution 做了:
z[isbad] = numpy.NaN
z = numpy.ma.masked_invalid(z)
vmin, vmax = z.min(), z.max()
z = z.filled(fill_value=-999)
levels = numpy.linspace(vmin, vmax, n_points)
plt.tricontourf(x, y, z, levels=levels)
我有一些 numpy 数组,其中包含我将在二维网格上可视化的数据。有些数据是非物理的,我想屏蔽这些数据。但是,我不知道如何正确设置 tricontour
的掩码属性。我试过了:
import matplotlib.pyplot as mp
import numpy as np
with open('some_data.dat', 'r') as infile:
x, y, z = np.loadtxt(infile, usecols=(0, 1, 2), unpack=True)
isbad = np.less(z, 1.4) | np.greater(z, 2.1)
mp.tricontourf(x, y, z, mask = isbad)
但是结果图根本就没有被屏蔽。我尝试了 masking part of a contourf plot in matplotlib,即
z2 = np.ma.array(z, mask= isbad)
mp.tricontourf(x, y, z2)
这也没有用。我想使用 tricontourf
instrad of contourf
,因为我不想对我的数据进行网格化。
z[isbad] = np.nan
调用 tricontourf 时导致分段错误
这是图,红色是我想标记为非物理的。
技巧来了。我需要收集三角形的索引(它们是 z 的索引!),评估它们是否好,然后只接受至少一个角有效的三角形(将维度从 (ntri, 3) 减少到 ntri
triang = tr.Triangulation(x, y)
mask = np.all(np.where(isbad[triang.triangles], True, False), axis=1)
triang.set_mask(mask)
colplt = mp.tricontourf(triang, z)
mp.colorbar()
受此启发link:http://matplotlib.org/examples/pylab_examples/tripcolor_demo.html
wsj 的回答对我不起作用,因为它没有删除某些屏蔽点(我认为不是所有节点都不好)。
This solution 做了:
z[isbad] = numpy.NaN
z = numpy.ma.masked_invalid(z)
vmin, vmax = z.min(), z.max()
z = z.filled(fill_value=-999)
levels = numpy.linspace(vmin, vmax, n_points)
plt.tricontourf(x, y, z, levels=levels)