【问题标题】:masking part of a contourf plot in matplotlib在 matplotlib 中掩盖轮廓图的一部分
【发布时间】:2012-04-05 13:16:00
【问题描述】:

我正在尝试使用 contourf 在 matplotlib 中生成填充等高线图。靠近图底部的锯齿状模式中缺少数据。等高线图不仅在原始数据被屏蔽的地方变成空白,而且在等高线算法由于没有足够的良好数据邻域而无法干净地插值的地方也是空白。

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

在上一个帖子中,我学习了如何通过绘制第一张图像然后用另一张掩盖坏区域的图像覆盖它来为图像执行此操作。模拟将是下面的代码 sn-p 但它不适用于轮廓......我无法让 bad_data imshow 掩盖扩展的轮廓图。有可能吗?

谢谢, 以利

import matplotlib.pyplot as plt
lev = [0.0,0.1,0.2,0.5,1.0,2.0,4.0,8.0,16.0,32.0]           
norml = colors.BoundaryNorm(lev, 256)
# this is the contour plot, using extended_data so that the contours are plausibly extended
cs = plt.contourf(x,z,extended_data,levels = lev, cmap = cm.RdBu_r,norm = norml) 
# now the attempt to cover it up -- but imshow will not cover up the original plot as it will with another image
bad_data = np.ma.masked_where(~data.mask, data.mask, copy=True) 
plt.imshow(bad_data, interpolation='nearest', aspect = 'auto', cmap=cm.gray)
plt.show()

【问题讨论】:

  • 我应该补充一点,因为这篇文章我意识到我可以识别该区域并使用 fill() 来屏蔽该区域。因此,紧迫性较低,但知道是否可以做到这一点仍然很有价值。
  • 假设您有一个 5x5 数组,并且缺少索引 [1, 1],您希望看到什么?索引 [1, 1] 会被绘制为标记吗?
  • 你能发布一个最小的工作示例吗?

标签: python matplotlib contour


【解决方案1】:

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

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

通过使用contourf绘制以上内容,

plt.contourf(d)
plt.show()

我明白了:

不显示(空白)掩码值(d

# 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()

我不知道在这种情况下使用掩码数组有多快,但无论如何我会这样做。如果您想要不同的颜色而不是空白点(白色),则需要为下面的轴块着色,因为 contourf 实际上不会在没有数据或屏蔽数据的情况下绘制任何内容:

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

得到:

【讨论】:

    猜你喜欢
    • 2015-07-31
    • 2023-03-23
    • 1970-01-01
    • 2013-10-23
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 2022-01-13
    • 2014-12-12
    相关资源
    最近更新 更多