python matplotlib plot hist2d with normalized masked numpy array

时间:2013-08-15 12:55:14

标签: python numpy matplotlib

我想使用matplotlib.pyplot.hist2d绘制2d直方图。作为输入我掩盖了numpy.ma数组。这样的工作原理很好:

hist2d (arr1,arr2,cmin=1)

但是如果我想规范化数组,那么我总是使用normed = True关键字来获取0到1之间的值

hist2d (arr1,arr2,cmin=1, normed=True)

我收到错误

.../numpy/ma/core.py:3791: UserWarning: Warning: converting a masked element to nan.
  warnings.warn("Warning: converting a masked element to nan.")
.../matplotlib/colorbar.py:561: RuntimeWarning: invalid value encountered in greater
  inrange = (ticks > -0.001) & (ticks < 1.001)
.../matplotlib/colorbar.py:561: RuntimeWarning: invalid value encountered in less
  inrange = (ticks > -0.001) & (ticks < 1.001)
.../matplotlib/colors.py:556: RuntimeWarning: invalid value encountered in less
  cbook._putmask(xa, xa < 0.0, -1)

我知道如何绕过这个并仍然得到标准化的2d直方图?

1 个答案:

答案 0 :(得分:7)

由于cmin,它与normed=True无关。删除cmin(或将其设置为0)将使其正常工作。如果您确实需要过滤,可以考虑使用numpy的2d直方图功能,然后屏蔽输出。

a = np.random.randn(1000)
b = np.random.randn(1000)

a_ma = np.ma.masked_where(a > 0, a)
b_ma = np.ma.masked_where(b < 0, b)

bins = np.arange(-3,3.25,0.25)

fig, ax = plt.subplots(1,3, figsize=(10,3), subplot_kw={'aspect': 1})

hist, xbins, ybins, im = ax[0].hist2d(a_ma,b_ma, bins=bins, normed=True)

hist, xbins, ybins = np.histogram2d(a_ma,b_ma, bins=bins, normed=True)
extent = [xbins.min(),xbins.max(),ybins.min(),ybins.max()]

im = ax[1].imshow(hist.T, interpolation='none', origin='lower', extent=extent)
im = ax[2].imshow(np.ma.masked_where(hist == 0, hist).T, interpolation='none', origin='lower', extent=extent)

ax[0].set_title('mpl')
ax[1].set_title('numpy')
ax[2].set_title('numpy masked')

enter image description here