Reputation: 51
I have x, y and z data which looks like the following (sample data):
x_data = [2, 2, 2, 3, 3, 3, 1, 1, 1, 4, 4, 4]
y_data = [16, 64, 32, 64, 32, 16, 16, 32, 64, 32, 16, 64]
z_data = [64, 31, 29, 78, 72, 63, 93, 40, 54, 35, 44, 3]
Since I can map every z value to an unique x/y data pair, I would like to plot it as a filled countour plot in matplotlib. contourf
requires x and y to be either meshgrids or to be the size of the corresponding dimension of z.
At the moment the code I use to prepare the data is the following:
mesh_x, mesh_y = np.meshgrid(np.unique(x_data), np.unique(y_data))
mesh_z = np.zeros(mesh_x.shape)
for x, y, z in zip(x_data, y_data, z_data):
mesh_z[np.bitwise_and(y == mesh_y, x == mesh_x)] = z
Since np.unique
reorders the values, I can not use np.reshape(z_data, mesh_x.shape)
to create the needed data structure.
Although this solution works, I feel like there must be a better way to archieve this.
Upvotes: 2
Views: 2231
Reputation: 59731
I think this does what you want:
import numpy as np
import matplotlib.pyplot as plt
x_data = np.asarray([2, 2, 2, 3, 3, 3, 1, 1, 1, 4, 4, 4])
y_data = np.asarray([16, 64, 32, 64, 32, 16, 16, 32, 64, 32, 16, 64])
z_data = np.asarray([64, 31, 29, 78, 72, 63, 93, 40, 54, 35, 44, 3])
# Sort coordinates and reshape in grid
idx = np.lexsort((y_data, x_data)).reshape(4, 3)
# Plot
plt.contourf(x_data[idx], y_data[idx], z_data[idx])
Output:
Upvotes: 2