python - 如何使用 numpy.ma.masked_inside

标签 python numpy matplotlib masked-array

numpy.ma.masked_where用于屏蔽单个值。还有用于屏蔽间隔的 numpy.ma.masked_inside 。

但是我不太明白它应该如何工作。

I found this snippet :

import numpy.ma as M              
from pylab import *

figure()

xx = np.arange(-0.5,5.5,0.01) 
vals = 1/(xx-2)        
vals = M.array(vals)
mvals = M.masked_where(xx==2, vals)

subplot(121)
plot(xx, mvals, linewidth=3, color='red') 
xlim(-1,6)
ylim(-5,5) 

但是,我想做这样的事情(我知道这行不通):

mvals = M.masked_where(abs(xx) < 2.001 and abs(xx) > 1.999, vals)

因此我尝试使用masked_inside like this :

mvals = ma.masked_inside(xx, 1.999, 2.001)

但结果不是我想要的,它只是一条直线...我想要类似 this 的东西.

整个脚本是这样的:

def f(x):
    return  (x**3 - 3*x) / (x**2 - 4)

figure()
xx = np.arange(begin, end, precision)
vals = [f(x) for x in xx]
vals = M.array(vals)
mvals = ma.masked_inside(xx, 1.999, 2.001)
subplot(121)
plot(xx, mvals, linewidth=1, c='red')
xlim(-4,4)
ylim(-4,4)
gca().set_aspect('equal', adjustable='box')
show()

如何正确使用masked_inside

最佳答案

问题不在于np.masked_inside,而在于您在哪一点以及在哪个数组上使用它(您将其应用于之后您已经应用函数的值!) .

np.ma.masked_inside只是 np.ma.masked_where 的一个方便包装:

def masked_inside(x, v1, v2, copy=True):
    # That's the actual source code
    if v2 < v1:
        (v1, v2) = (v2, v1)
    xf = filled(x)
    condition = (xf >= v1) & (xf <= v2)
    return masked_where(condition, x, copy=copy)

如果你像这样应用它:

import numpy as np
import matplotlib.pyplot as plt

def f(x):
    return  (x**3 - 3*x) / (x**2 - 4)

# linspace is much better suited than arange for such plots
x = np.linspace(-5, 5, 10000)
# mask the x values
mvals = np.ma.masked_inside(x, 1.999, 2.001)  
mvals = np.ma.masked_inside(mvals, -2.001, -1.999)  

# Instead of the masked_inside you could also use
# mvals = np.ma.masked_where(np.logical_and(abs(x) > 1.999, abs(x) < 2.001), x) 

# then apply the function
vals = f(mvals)                  

plt.figure()
plt.plot(x, vals, linewidth=1, c='red')
plt.ylim(-6, 6)

然后输出看起来几乎就像您链接的输出:

enter image description here

关于python - 如何使用 numpy.ma.masked_inside,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41687389/

相关文章:

python - 使用字典将表情符号替换为文本

python - 使用 Matplotlib 在线图旁边绘制颜色条

python - 对数据框中的值进行排序

python - Numpy 数组广播规则

python - 词汇散布图是seaborn

python - Django 模板中的行着色基于 "ifchanged"?

使用 Soap + Request 进行 Python 网页抓取

python - np.argsort 排除零值

pycharm 中的 matplotlib 外部文档

python - 使用 numpy 分隔数组以在 python 中使用 matplotlib 进行绘图