【问题标题】:plotting two matrices in the same graph with matplotlib使用 matplotlib 在同一个图中绘制两个矩阵
【发布时间】:2021-03-12 03:26:58
【问题描述】:

我想在同一张图中绘制两个矩阵。这些矩阵的形状为 3x5。它们是使用 meshgrid 为大小为 3 和 5 的两个数组创建的(a 为 3 号,b 为 5 号)。矩阵的条目是使用数组中的值计算的,我想在图中显示,例如如果 M1 使用条目 a1 和 b1 计算,则 M1 应显示在图中两个索引相遇的位置。此外,图表的轴应标有两个数组的条目。

为确保更好地理解我的问题,我将在这篇文章中发布所需输出的图片。在我的特定用例中,两个矩阵的某些值将是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 新手,感谢任何帮助。

提前谢谢你!

【问题讨论】:

  • 你能举一个这两个矩阵的例子吗?
  • 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])
  • 在我贴的图片中的矩阵没有条目的例子中,我尝试用nan写,我希望这是正确的。
  • A) 这两个矩阵的大小是否总是相同(例如,都是 5x7)? B) 两个矩阵是否都填充了保证矩形的值(不是 M1 以M1 = ([5, 3, nan], [2, 5, 4],... 开头)?如果两个答案都是肯定的,则计算每个矩阵的非 NaN 值的最小/最大索引,并将这些坐标绘制为矩形。
  • @Mr.T A) 是的,两个矩阵的大小始终相同 B) 不,它们并不总是矩形.. 您为 M1 提供的示例是可能的。

标签: python matplotlib matrix


【解决方案1】:

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

【讨论】:

  • 感谢您的精彩回答。这正是我想做的。现在唯一要做的就是进一步阅读解决方案的文档。 :D
  • 我完全支持这一点。 matplotlib 文档非常好,但首先我会通过 tutorials。而且,大多数日常问题都可以通过修改example gallery 中的代码来解决。
猜你喜欢
  • 2017-11-01
  • 2015-07-04
  • 1970-01-01
  • 1970-01-01
  • 2011-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-21
相关资源
最近更新 更多