The Python Oracle

python matplotlib plot hist2d with normalised masked numpy array

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Ancient Construction

--

Chapters
00:00 Python Matplotlib Plot Hist2d With Normalised Masked Numpy Array
00:42 Accepted Answer Score 9
01:18 Thank you

--

Full question
https://stackoverflow.com/questions/1825...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #numpy #matplotlib

#avk47



ACCEPTED ANSWER

Score 9


Its because of the cmin, it doesnt go well with normed=True. Removing cmin (or set it at 0) will make it work. If you do need to filter you can consider using numpy's 2d histogram function and masking the output afterwards.

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