Warm tip: This article is reproduced from serverfault.com, please click

python-使用matplotlib在同一图中绘制两个矩阵

(python - plotting two matrices in the same graph with matplotlib)

发布于 2020-11-30 07:40:21

我想在同一张图中绘制两个矩阵。这些矩阵的形状为3x5。它们是使用meshgrid为大小为3和5的两个数组创建的(a为大小3,b为大小5)。矩阵的条目使用来自所述阵列中的值,这是我想在情节以显示计算,所以例如如果M 1是与条目的计算1和b 1中,M 1应该被示出,其中两个指数在满足该图。此外,图的轴应标记有两个数组的条目。

为了确保更好地理解我的问题,我将在这篇文章中发布所需输出的图片。在我的特定用例中,两个矩阵的某些值将为NaNs,因此我可以看到两个矩阵重叠的位置。这两个矩阵的一个示例是:

M1 = ([5, 3, nan], 
      [2, 5, nan], 
      [6, 7, nan], 
      [9, 10, nan], 
      [11, 12, nan])
M2 = ([nan, nan, nan],
      [nan, 1, 2], 
      [nan, 8, 5], 
      [nan, 6, 9], 
      [nan, nan, nan])

在此处输入图片说明 我确信这是一个基本问题,但是我是python的新手,感谢你的帮助。

先感谢你!

Questioner
lempy
Viewed
0
Mr. T 2020-11-30 22:41:38

我考虑过要找到每个矩阵的船体图形会有多困难,并且甚至不清楚矩阵中是否有孔。但是,为什么不让numpy / matplotlib完成所有工作呢?

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors

M1 = ([5,      3,      6,      7], 
      [2,      np.nan, 3,      6], 
      [6,      7,      8,      np.nan], 
      [9,      10,     np.nan, np.nan], 
      [11,     12,     np.nan, np.nan])

M2 = ([np.nan, np.nan, np.nan, np.nan],
      [np.nan, np.nan, 1,      2], 
      [np.nan, 4,      8,      5], 
      [np.nan, np.nan, 6,      9], 
      [np.nan, np.nan, np.nan, np.nan])

#convert arrays into truth values regarding the presence of NaNs
M1arr = ~np.isnan(M1)
M2arr = ~np.isnan(M2)

#combine arrays based on False = 0, True = 1
M1M2arr = np.sum([M1arr, 2 * M2arr], axis=0) 

#define color scale for the plot
cmapM1M2 = colors.ListedColormap(["white", "tab:blue", "tab:orange", "tab:red"])

cb = plt.imshow(M1M2arr, cmap=cmapM1M2)
cbt= plt.colorbar(cb, ticks=np.linspace(0, 3, 9)[1::2])
cbt.ax.set_yticklabels(["M1 & M2 NaN", "only M1 values", "only M2 values", "M1 & M2 values"])
plt.xlabel("a[i]")
plt.ylabel("b[i]")

plt.tight_layout()
plt.show()

样本输出: ![在此处输入图片描述

我一直保持方向,imshow因为这是打印输出时如何读取矩阵条目的方式。你可以通过更改以下行将此图像转换为通常的坐标表示形式:

cb = plt.imshow(M1M2arr, cmap=cmapM1M2, origin="lower")