简体   繁体   中英

Matplotlib imshow: how to apply a mask on the matrix

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?

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

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()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM