【问题标题】:Set mask for matplotlib tricontourf为 matplotlib tricontourf 设置掩码
【发布时间】:2015-03-10 13:03:04
【问题描述】:

我有一些 numpy 数组,其中包含我将在 2D 网格上可视化的数据。有些数据是非物理的,我想屏蔽这些数据。但是,我无法弄清楚如何正确设置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)

这也不起作用。我想使用contourftricontourf instrad,因为我不想对我的数据进行网格化。

z[isbad] = np.nan

调用 tricontourf 时导致分段错误

这是图,红色是我想标记为非物理的。

【问题讨论】:

    标签: python numpy matplotlib


    【解决方案1】:

    诀窍来了。我需要收集三角形的索引(它们是 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()
    

    受此链接启发:http://matplotlib.org/examples/pylab_examples/tripcolor_demo.html

    【讨论】:

    • 确实应该使用“any”而不是“all”,如果一个节点有一个NaN,使用all仍然会允许NaN值进入轮廓算法,并导致Segmentation faults
    • 我使用mask = np.sum(isbad[triang.triangles],axis=1)>1 来测试是否有 2 或 3 个节点是可疑的,因为我想查看至少 1 个节点在范围内的结果。
    【解决方案2】:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-26
      • 1970-01-01
      相关资源
      最近更新 更多