Home > Back-end >  Creating Density/Heatmap Plot from Coordinates and Magnitude in Python
Creating Density/Heatmap Plot from Coordinates and Magnitude in Python

Time:03-04

I have some data which is the number of readings at each point on a 5x10 grid, which is in the format of;

X = [1, 2, 3, 4,..., 5]
Y = [1, 1, 1, 1,...,10]
Z = [9,8,14,0,89,...,0]

I would like to plot this as a heatmap/density map from above, but all of the matplotlib graphs (incl. contourf) that I have found are requiring a 2D array for Z and I don't understand why.

CodePudding user response:

They expect a 2D array because they use the "row" and "column" to set the position of the value. For example, if array[2, 3] = 5, then when x is 2 and y is 3, the heatmap will use the value 5.

So, let's try transforming your current data into a single array:

>>> array = np.empty((len(set(X)), len(set(Y))))
>>> for x, y, z in zip(X, Y, Z):
        array[x-1, y-1] = z

If X and Y are np.arrays, you could do this too (enter image description here

  • Related