【问题标题】:Matplotlib hist2d() and numpy masked_where()?Matplotlib hist2d() 和 numpy masked_where()?
【发布时间】:2020-07-01 16:16:09
【问题描述】:

我可能误解了numpy.ma.masked_where() 的工作原理,但它似乎不适用于matplotlib hist2d()

在下面的代码中,我创建了一个ndarray,将其屏蔽,然后用matplotlib.pyplot.plot() 绘制原始和屏蔽ndarrays。这行得通。

但是,当我尝试使用matplotlib.pyplot.hist2d() 绘制两者时,似乎没有考虑掩码。我已经使用 matplot lib 1.3.1 和 3.2.1 以及 numpy 1.18.5 对此进行了测试。

有什么建议吗?

import math
import numpy as np
import time
import sys

import numpy.ma as ma

import matplotlib
import matplotlib.pyplot as plt
from scipy.stats import expon, poisson, uniform, norm

print(matplotlib.__version__, np.__version__)
nSiz=10000
maxx, maxy = 1.0, 10.0
x, y, z = uniform.rvs(scale=maxx, size=nSiz), uniform.rvs(scale=maxy, size=nSiz), norm.rvs(scale=1.0, size=nSiz)
binx, biny = np.linspace(0, maxx, 20), np.linspace(0, maxy, 20) 

d = np.array([(xx, yy, zz) for xx, yy, zz in zip(x, y, z)], dtype=[('X', 'f4'), ('Y', 'f4'), ('Z', 'f4')])

print("Col titles: " + str(d.dtype.names))

dc = ma.masked_where(d['X'] < 0.5, d)   # Mask data

fig, axx = plt.subplots(2, 2, figsize=(10, 10), dpi=300)
ax = axx.ravel()

ax[0].plot(d['X'], d['Y'], 'bv', ms=3)
ax[1].plot(dc['X'], dc['Y'], 'ro', ms=6, alpha=0.1) ### Mask seems to work

ax[2].hist2d(d['X'], d['Y'], bins=[binx, biny], cmap='Blues')
ax[3].hist2d(dc['X'], dc['Y'], bins=[binx, biny], cmap='Blues') ### Mask doesn't seem to work

for axx in ax:
    axx.set_xlabel(d.dtype.names[0], fontsize = 15)
    axx.set_ylabel(d.dtype.names[1], fontsize = 15)
    axx.set_xlim(0.0, maxx)
    axx.set_ylim(0.0, maxy)
    
ax[0].set_title('No cut')
ax[1].set_title('Cut')
plt.show()

最后的情节不正确:

【问题讨论】:

  • plot hist2d with normalised masked numpy array 建议使用np.histogram 计算并对结果应用掩码。由于直方图结果是与输入不同的类型,因此需要调整掩码。目前尚不清楚这在您想要的用例中是否可行。

标签: matplotlib numpy-ndarray


【解决方案1】:

在我的情况下,一个简单的解决方案是不使用:

dc = ma.masked_where(d['X'] &lt; 0.5, d)

而是简单地将该命令替换为:

dc = d[d['X'] &lt; 0.5]

这对我有用(尽管我仍然不知道numpy.ma.masked_where() 的用途)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-17
    相关资源
    最近更新 更多