Python matplotlib contourf plot

问题描述 投票:-1回答:1

我有一个关于matplotlib和contourf的问题。

我正在使用matplotlib的最新版本和python3.7。基本上我必须矩阵我想绘制在相同的等高线图但使用不同的色图。一个重要的方面是,例如,如果我们具有零矩阵A和矩阵B且形状=(10,10),则矩阵A不等于零的位置是矩阵B非零的位置,反之亦然。

换句话说,我想用不同的颜色绘制两种不同的面具。

谢谢你的时间。

编辑:

我在这里添加一个例子

import numpy
import matplotlib.pyplot as plt

matrixA=numpy.random.randn(10,10).reshape(100,)
matrixB=numpy.random.randn(10,10).reshape(100,)

mask=numpy.random.uniform(10,10)
mask=mask.reshape(100,)

indexA=numpy.where(mask[mask>0.5])[0]
indexB=numpy.where(mask[mask<=0.5])[0]

matrixA_masked=numpy.zeros(100,)
matrixB_masked=numpy.zeros(100,)
matrixA_masked[indexA]=matrixA[indexA]
matrixB_masked[indexB]=matrixB[indexB]

matrixA_masked=matrixA_masked.reshape(100,100)
matrixB_masked=matrixB_masked.reshape(100,100)

x=numpy.linspace(0,10,1)
X,Y = numpy.meshgrid(x,x)
plt.contourf(X,Y,matrixA_masked,colormap='gray')
plt.contourf(X,Y,matrixB_masked,colormap='winter')
plt.show()

我想要的是能够使用出现在同一图中的不同色彩图。因此,例如在图中将存在分配给具有轮廓颜色的矩阵A的部分(和矩阵B发生的0),并且矩阵B具有不同的颜色图。

在其他工作中,contourf图的每个部分对应于一个矩阵。我正在绘制机器学习模型的决策表面。

python matplotlib contourf
1个回答
1
投票

我在你的代码中偶然发现了一些错误,所以我创建了自己的数据集。要在一个图上有两个颜色图,您需要打开一个图并定义轴:

import numpy
import matplotlib.pyplot as plt

matrixA=numpy.linspace(1,20,100)
matrixA[matrixA >= 10] = numpy.nan
matrixA_2 = numpy.reshape(matrixA,[50,2])

matrixB=numpy.linspace(1,20,100)
matrixB[matrixB <= 10] = numpy.nan
matrixB_2 = numpy.reshape(matrixB,[50,2])

fig,ax = plt.subplots()
a = ax.contourf(matrixA_2,cmap='copper',alpha=0.5,zorder=0)
fig.colorbar(a,ax=ax,orientation='vertical')
b=ax.contourf(matrixB_2,cmap='cool',alpha=0.5,zorder=1)
fig.colorbar(b,ax=ax,orientation='horizontal')
plt.show()

enter image description here

你也会看到我改变了alphazorder

我希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.