Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 848
Learning is a mess Avatar asked Oct 07 '15 11:10

Learning is a mess


1 Answers

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

like image 75
Ed Smith Avatar answered Oct 16 '22 22:10

Ed Smith