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

plotting two matrices in the same graph with matplotlib

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

I want to plot two matrices in the same graph. These matrices have the shape 3x5. They were created using meshgrid for two arrays of the size 3 & 5 (a is size 3, b is size 5). The entries of the matrices were calculated using the values from the arrays, which I want to show in the plot, so e.g. if M1 was calculated with the entries a1 and b1, M1 should be shown where the two indices meet in the diagram. Also, the axis of the diagram should be labeled with the entries of the two arrays.

To ensure a better understanding of my question, I will post a picture of the desired output in this post. In my specific usecase, some values of the two matrices will be NaNs, so I can see, where the two matrices overlap. An example of the two matrices would be:

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

enter image description here I am sure this is a basic question, but I am new to python and appreciate any help.

Thank you in advance!

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

I thought about how difficult it will be to find the hull figure of each matrix, and it is not even clear if there might be holes in your matrix. But why don't we let numpy/matplotlib do all the work?

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

Sample output: ![enter image description here

I have kept the orientation of imshow because this is how you would read the matrix entries when printed out. You can invert this image into the usual coordinate representation by changing this line:

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