Convert X,Y,Z Values to Matrixplot

189 views Asked by At

I have the following lists:

x_list = [7,10,3,9,9]
y_list = [2,5,1,3,2]

z_list = [4,1,5,2,3]

For each x value and y value there is a zvalue. For example: x=7and y=2have the zvalue of 4.

I would like to convert this into a matrix such as:

enter image description here

… to be able to create a matrix-plot with the correct x- and y- axis and a colorbar (colorbar is missing here, and it would be nice to have the zero values as black color):

enter image description here

It is rather straightforward to do in Excel, but I am having difficulties doing it in python, since I am quite new to matplotlib.

Edit

I might use plt.imshow() to make the plot

1

There are 1 answers

1
HansHirse On

NumPy's unique and meshgrid functions are your friends here to set up the proper grid from your coordinates. Then, you just need to find the proper indices in the resulting X and Y, that correspond to your coordinates. Finally, in some all-zero Z matrix with the same dimensions as X and Y, you can set the elements at the just found indices to your original z data.

Here's some code:

import numpy as np

x = np.array([7, 10, 3, 9, 9])
y = np.array([2,  5, 1, 3, 2])
z = np.array([4,  1, 5, 2, 3])

# Calculate X, Y grid from x and y, initialize Z data with zero
X, Y = np.meshgrid(np.unique(x), np.unique(y))
Z = np.zeros(X.shape)

# Find proper indices in grid, and set Z values accordingly
idx = np.squeeze([np.argwhere(np.logical_and(X == x[idx], Y == y[idx])) for idx in np.int32(np.arange(x.size))])
Z[idx[:, 0], idx[:, 1]] = z
print(Z)

And, the output is:

[[5. 0. 0. 0.]
 [0. 4. 3. 0.]
 [0. 0. 2. 0.]
 [0. 0. 0. 1.]]

Regarding the plotting: I can't think of a Matplotlib function to create a plot similar to the shown. So, maybe give an additional hint, which function you have in mind.

Hope that helps!