Matplotlib imshow:如何在矩阵上应用掩码 [英] Matplotlib imshow: how to apply a mask on the matrix

查看:39
本文介绍了Matplotlib imshow:如何在矩阵上应用掩码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以图形方式分析二维数据. matplotlib.imshow 在这方面非常有用,但我认为,如果我可以从矩阵中排除某些单元格(感兴趣范围之外的值),则可以利用更多的信息.我的问题是这些值在我感兴趣的范围内展平"了颜色图.排除这些值后,我可以拥有更高的色彩分辨率.

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.

我知道如何在我的矩阵上应用蒙版以排除这些值,但它在应用蒙版后返回一个 1d 对象:

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

有没有办法将掩码传递给 imshow 如何重建二维数组?

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

推荐答案

您可以使用 numpy.ma.mask_where 来保留数组形状,例如

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

这篇关于Matplotlib imshow:如何在矩阵上应用掩码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆