making a contour plot using irregular x y z data

Viewed 375

I want to make a beautiful contour map using my data attached and want to write A B C D E F G H on the map itself.

dt   x      y       z
A  31.53  77.95   0.112
B  31.40  78.35   0.032
C  31.66  78.03  -0.001
D  31.48  77.75  -0.092
E  32.28  78.45  -0.113
F  31.99  76.42  -0.184
G  31.64  77.34  -0.016
H  32.50  75.62  -0.121

My script is here :

import matplotlib.pyplot as plt
import numpy as np

data=np.loadtxt("data.txt",dtype='str')

plt.tricontour(data[:,2],data[:,1],data[:,3],  colors='black');
#plt.tricontour(x,y,z)
plt.show()

I am getting the error

self.triangles, self._neighbors = _qhull.delaunay(x, y)
ValueError: x and y must be 1D arrays of the same length

please suggest a better solution for this.Thanks in advance.

i need plots like https://jakevdp.github.io/PythonDataScienceHandbook/04.04-density-and-contour-plots.html

1 Answers

When you use the method: np.loadtxt(), you get an ndarray object which is different from pandas Dataframe because the first index are the rows and not the columns.

np.loadtxt() documentation: https://numpy.org/doc/stable/reference/generated/numpy.loadtxt.html

This code should do the job:

import matplotlib.pyplot as plt
import numpy as np

data = np.loadtxt("data.txt", dtype='str')

# Lets check out the internal order of the object.
print(data[1])

# so the first place are rows and not the columns.
# lets take the column content:
x = []
y = []
z = []
for i in range(1, len(data)):
    x.append(float(data[i][1]))
    y.append(float(data[i][2]))
    z.append(float(data[i][3]))

plt.tricontour(x, y, z, colors='black')
plt.show()

Output:

enter image description here

After coloring: enter image description here

Related