在轮廓中绘制 NaNs 区域的边界

Plot borders of NaNs region in contour

我正在尝试用 NaN 绘制一些数据的等高线图(无解)。我想用黑线表示 NaN 的边界。到目前为止,我只找到了如何孵化整个 NaN 区域 (hatch a NaN region in a contourplot in matplotlib),但我只想要轮廓。

fig, ax = plt.subplots()

d = np.random.rand(10, 10)
d[2, 2], d[3, 5] = np.nan, np.nan

plt.contour(d)
plt.show()

我得到:

我想要:

您可以绘制另一个被屏蔽区域的轮廓。为此,可以使用 numpy.ma 数组屏蔽数据。然后使用它的掩码在接近(但不完全)零的水平上绘制另一个轮廓。

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

d = np.random.rand(10, 10)

mask = np.zeros(d.shape, dtype=bool)
mask[2, 2], mask[3, 5] = 1, 1

masked_d = np.ma.array(d, mask=mask)

plt.contour(masked_d)

plt.contour(mask, [0.01], colors="k", linewidths=3)

plt.show()