Search code examples
pythonmatplotlibnumpy-ndarraycontourapproximation

Converting Arrays of Data into an Approximated Contour Line Map (Python)


I have 3 arrays formed from 3 lists:

 x = np.array(xlist)
 y = np.array(ylist)
 z = np.array(zlist)

where each list represents the x coords, y coords, and the weight for each specified coord. There are around 3000 values in each list (corresponding to 3000 individual points each with some weight z).

The thing is, these values are very precise floats to the 10th degree of precision. However, What I want to do is be able to create “n” number of roughly evenly spaced contour lines (not fill-colored, just a few closed, thin lines) that have a threshold for approximation.

Even though my z points are very precise and likely no 2 are exact, there are a lot of them, and as a whole form a “hollowed mountain” like shape when plotted in 3d (so in my imagination, the contour lines would be just evenly spaced horizontal slices).

I do not have a function that represents z = f(x,y). Therefore I cannot just do this:

plt.contour(x,y,z, contour_num)

As this reveals the expected error that z has to be a 2D array.

However, z is just a set of points only related to x and y based on location.

How can I plot this “approximated contour map” without a meshgrid (are there manual methods of doing this directly with data?)?

EDIT NOTE:

Also, just so you know, the error I get when I try something like this is “Value Error: cannot reshape array of size 3000 into shape (3000,3000)”:

 X,Y = np.meshgrid(x,y)
 Z = z.reshape(3000,3000)
 plt.contour(X,Y,Z)
 plt.show()

If there is no other way to create a contour line map, then why does this not work? How can I make it work?


Solution

  • Ok I answered my own question. The way to do this is via plt.tricontour(x,y,z,num_contours). Works perfectly.