Matplotlib imshow: how to apply a mask on the matrix

Learning is a mess picture Learning is a mess · Oct 7, 2015 · Viewed 9.9k times · Source

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?

Answer

Ed Smith picture Ed Smith · Oct 7, 2015

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

enter image description here