Matplotlib imshow: how to apply a mask on the matrix

时光怂恿深爱的人放手 提交于 2019-12-08 16:57:00

问题


I am trying to analyse graphically 2d data. matplotlib.imshow is very useful in that but I feel that I could make even more use of that if I could exclude some cells from my matrix, values of outside of a range of interest. My problem is that these values ''flatten'' the colormap in my range of interest. I could have more color resolution after excluding these values.

I know how to apply a mask on my matrix to exclude these values, but it returns a 1d object after applying the mask:

mask = (myMatrix > lowerBound) & (myMatrix < upperBound)
myMatrix = myMatrix[mask] #returns a 1d array :(

Is there a way to pass the mask to imshow how to reconstruct a 2d array?


回答1:


You can use numpy.ma.mask_where to preserve the array shape, e.g.

import numpy as np
import matplotlib.pyplot as plt

lowerBound = 0.25
upperBound = 0.75
myMatrix = np.random.rand(100,100)

myMatrix =np.ma.masked_where((lowerBound < myMatrix) & 
                             (myMatrix < upperBound), myMatrix)


fig,axs=plt.subplots(2,1)
#Plot without mask
axs[0].imshow(myMatrix.data)

#Default is to apply mask
axs[1].imshow(myMatrix)

plt.show()


来源:https://stackoverflow.com/questions/32991649/matplotlib-imshow-how-to-apply-a-mask-on-the-matrix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!