Python 在matplotlib中屏蔽轮廓图的一部分

Python 在matplotlib中屏蔽轮廓图的一部分,python,matplotlib,contour,Python,Matplotlib,Contour,我正在尝试使用contourf在matplotlib中生成填充等高线图。图形底部附近的锯齿状图案中缺少数据。等高线图不仅在原始数据被屏蔽的地方是空白的,而且在等高线算法无法清晰插值的地方也是空白的,因为好数据的邻域不足 我知道如何扩展数据集以在这些口袋中生成合理的轮廓。然而,如果我绘制扩展数据,我得到的轮廓填充无处不在。我想用黑色或白色来掩盖原始数据丢失的区域 在前面的一个线程中,我学习了如何对一个图像执行此操作,方法是绘制第一个图像,然后用另一个图像覆盖它,以掩盖不好的区域。模拟将是下面的代码

我正在尝试使用contourf在matplotlib中生成填充等高线图。图形底部附近的锯齿状图案中缺少数据。等高线图不仅在原始数据被屏蔽的地方是空白的,而且在等高线算法无法清晰插值的地方也是空白的,因为好数据的邻域不足

我知道如何扩展数据集以在这些口袋中生成合理的轮廓。然而,如果我绘制扩展数据,我得到的轮廓填充无处不在。我想用黑色或白色来掩盖原始数据丢失的区域

在前面的一个线程中,我学习了如何对一个图像执行此操作,方法是绘制第一个图像,然后用另一个图像覆盖它,以掩盖不好的区域。模拟将是下面的代码片段,但它不适用于轮廓。。。我不能用坏的数据来掩盖扩展的轮廓图。可能吗

谢谢, 伊莱


如果我错了,请纠正我,但据我所知,您有这种情况:

import numpy as np
import matplotlib.pyplot as plt
# generate some data with np.nan values (the missing values)
d = np.random.rand(10, 10)
d[2, 2], d[3, 5] = np.nan, np.nan
# and in your case you actually have masked values too:
d = np.ma.array(d, mask=d < .2)
# now all of the above is just for us to get some data with missing (np.nan) and
# masked values
我得到:

它不显示(空白)屏蔽值(d<.2)或np.nan值(d[2,2],d[3,5])!您希望matplotlib只显示屏蔽的值。因此,我们可以这样做:

# the following line is replaced by your interpolation routine for
# removing np.nan values
d[np.isnan(d)] = 1
# then because we use the masked array only the masked values will still be masked
# but the np.nan values which were replaced through the interpolation algorithm
# will show up if we do the contourf plot
plt.contourf(d)
plt.show()

我不知道在这种情况下使用屏蔽数组的速度有多快,但无论如何,我会这样做。如果你想要一个不同的颜色而不是空白点(WHIT),你需要把下面的轴的颜色涂上,因为轮廓线实际上没有绘制没有数据的任何东西,或者屏蔽数据:

# make the background dark gray (call this before the contourf)
plt.gca().patch.set_color('.25')
plt.contourf(d)
plt.show()
要获得:


我应该补充一点,因为这篇文章我意识到我可以识别区域并使用fill()来屏蔽区域。因此紧迫性较低,尽管知道是否可以做到这一点仍然很有价值。假设您有一个5x5数组,并且缺少索引[1,1],您希望看到什么?索引[1,1]会被画成一个标记吗?你能给出一个简单的工作示例吗?
# the following line is replaced by your interpolation routine for
# removing np.nan values
d[np.isnan(d)] = 1
# then because we use the masked array only the masked values will still be masked
# but the np.nan values which were replaced through the interpolation algorithm
# will show up if we do the contourf plot
plt.contourf(d)
plt.show()
# make the background dark gray (call this before the contourf)
plt.gca().patch.set_color('.25')
plt.contourf(d)
plt.show()