首页 > 解决方案 > 使用不规则 xyz 数据制作等高线图

问题描述

我想用我附加的数据制作一个漂亮的等高线图,并想在地图本身上写 ABCDEFGH。

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

我的脚本在这里:

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()

我收到错误

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

请为此提出更好的解决方案。在此先感谢。

我需要像https://jakevdp.github.io/PythonDataScienceHandbook/04.04-density-and-contour-plots.html这样的图

标签: pythonpandasnumpymatplotlibseaborn

解决方案


当您使用 method:np.loadtxt()时,您会得到一个与 pandas Dataframe 不同的 ndarray 对象,因为第一个索引是而不是列。

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

这段代码应该可以完成这项工作:

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()

输出:

在此处输入图像描述

上色后: 在此处输入图像描述


推荐阅读