繁体   English   中英

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

[英]plotting two matrices in the same graph with matplotlib

我想在同一张图中 plot 两个矩阵。 这些矩阵的形状为 3x5。 它们是使用 meshgrid 为大小 3 和 5 的两个 arrays(a 是 3 号,b 是 5 号)创建的。 矩阵的条目是使用 arrays 中的值计算的,我想在 plot 中显示,因此例如,如果 M 1使用条目 a 1和 b 1计算,则 M 1应该显示在两个索引相遇的地方图。 此外,图表的轴应标有两个 arrays 的条目。

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

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 的新手,感谢任何帮助。

先感谢您!

我想过要找到每个矩阵的外壳图会有多困难,甚至不清楚你的矩阵中是否有洞。 但是我们为什么不让 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()

样品 output: ![在此处输入图像描述

我保留了imshow的方向,因为这是您在打印输出时读取矩阵条目的方式。 您可以通过更改此行将此图像反转为通常的坐标表示:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM