多次屏蔽Numpy数组会产生错误的结果

时间:2017-10-19 19:58:21

标签: python numpy matplotlib

我试图根据另外两个数组的条件在多个位置屏蔽单个数组。当我这样做然后绘制原始数组和它被掩盖的数组时,数据不会在正确的位置被一致地掩盖。下面是一个工作示例代码,可以重现问题以及结果图。

import numpy as np
import matplotlib.pyplot as plt

f1 = np.random.randint(51, size=150)
lt_vals = np.arange(0,25,1)
alt_vals = np.arange(0,15,1)
alt = np.tile(alt_vals,10)
lt = np.tile(lt_vals, 6)
x_vals = range(len(f1))

f1m = np.ma.masked_where((lt>5) & (lt<20), f1)
f1am = np.ma.masked_where(alt>5, f1m)


variables = [f1am, alt, lt]
ylabels = ['Function', 'Sim Alt', 'Sim Time']
number_of_subplots= len(variables)

plt.figure(figsize = (12,12))
for i,j,k in zip(range(number_of_subplots), variables, ylabels):  
    ax1 = plt.subplot(number_of_subplots,1,i+1)
    ax1.plot(x_vals,j)
    ax1.set_ylabel(k)

plt.show()

Example from Code

正如您所看到的,顶部面板中的数据应该在第二个面板大于5的任何位置被屏蔽,而第三个面板的任何位置都大于5但小于20.顶部面板中显示的第二组数据是显然在大于5的时候显示,这正是我的问题。任何人都有任何猜测如何从中获得正确的行为?谢谢!

- 将会

1 个答案:

答案 0 :(得分:0)

屏蔽肯定在问题的代码中正常工作。您可以使用fill_between可视化屏蔽的范围。此外,共享所有轴可以更容易地比较三个图。

import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["axes.xmargin"] = 0
plt.rcParams["axes.ymargin"] = 0

f1 = np.random.randint(51, size=150)
lt_vals = np.arange(0,25,1)
alt_vals = np.arange(0,15,1)
alt = np.tile(alt_vals,10)
lt = np.tile(lt_vals, 6)
x_vals = range(len(f1))

f1m = np.ma.masked_where((lt>5) & (lt<20), f1)
f1am = np.ma.masked_where(alt>5, f1m)


variables = [f1am, alt, lt]
ylabels = ['Function', 'Sim Alt', 'Sim Time']
number_of_subplots= len(variables)

fig, axes = plt.subplots(nrows=3, sharex=True)
for i,j,k in zip(range(number_of_subplots), variables, ylabels):  
    ax1 = axes[i]
    ax1.plot(x_vals,j, marker=".")
    ax1.set_ylabel(k)

axes[1].fill_between(x_vals,alt.max(),0, where=alt>5, alpha=0.2)
axes[2].fill_between(x_vals,lt.max(),0, where=(lt>5) & (lt<20), alpha=0.2)
axes[0].fill_between(x_vals,51,0, where=((lt>5) & (lt<20)) | (alt>5) , alpha=0.2)
plt.show()

enter image description here

在蒙版区域外有一些单点不会在线条图中显示,因此您可以使用标记"."来显示它们。