簡體   English   中英

掩蓋matplotlib中的contourf圖的一部分

[英]masking part of a contourf plot in matplotlib

我正在嘗試使用contourf在matplotlib中生成一個填充的等高線圖。 在圖底部附近的鋸齒狀圖案中缺少數據。 輪廓圖不僅在原始數據被遮蓋的地方變成空白,而且在口袋中也是空白的,其中輪廓算法不能干凈地插入,因為沒有足夠的良好數據鄰域。

我知道如何擴展數據集以在這些口袋中產生合理的輪廓。 但是,如果我繪制擴展數據,我會在任何地方獲得輪廓填充。 我想掩蓋原始數據缺失的黑色或白色區域。

在之前的一個帖子中,我通過繪制第一張圖像然后用掩蓋壞區域的另一張圖像覆蓋它來學習如何為圖像做到這一點。 模擬將是下面的代碼片段,但它不適用於輪廓......我無法通過bad_data imshow來掩蓋擴展的contourf圖。 可能嗎?

謝謝,Eli

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

如果我錯了,請糾正我,但據我所知你有這種情況:

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

在此輸入圖像描述

我不知道在這種情況下使用蒙面數組的速度有多快,但無論如何這就是我要做的。 如果你想要一個不同的顏色而不是空白點(白色)你需要為下面的軸的色塊着色,因為contourf實際上不會繪制任何沒有數據或掩蓋數據的東西:

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

要得到:

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM