我正在尝试使用Python中的Matplotlib制作以下数据的等高线图。该数据的格式如下:
# x y height
77.23 22.34 56
77.53 22.87 63
77.37 22.54 72
77.29 22.44 88
实际上,这些数据包含近10000个点,我从一个输入文件中读取。然而,z的可能值的集合很小(介于50-90之间,为整数),我希望对于每个这样不同的z,都有一条等值线。
以下是我的代码 -
import matplotlib
import numpy as np
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import csv
import sys
# read data from file
data = csv.reader(open(sys.argv[1], 'rb'), delimiter='|', quotechar='"')
x = []
y = []
z = []
for row in data:
try:
x.append(float(row[0]))
y.append(float(row[1]))
z.append(float(row[2]))
except Exception as e:
pass
#print e
X, Y = np.meshgrid(x, y) # (I don't understand why is this required)
# creating a 2D array of z whose leading diagonal elements
# are the z values from the data set and the off-diagonal
# elements are 0, as I don't care about them.
z_2d = []
default = 0
for i, no in enumerate(z):
z_temp = []
for j in xrange(i): z_temp.append(default)
z_temp.append(no)
for j in xrange(i+1, len(x)): z_temp.append(default)
z_2d.append(z_temp)
Z = z_2d
CS = plt.contour(X, Y, Z, list(set(z)))
plt.figure()
CB = plt.colorbar(CS, shrink=0.8, extend='both')
plt.show()
这里是一小部分数据的图表 -
![enter image description here](https://istack.dev59.com/q4M2p.webp)
![enter image description here](https://istack.dev59.com/bvYtV.webp)
NaN
值引起的。如果您检查输入文件(您发送给我的那个文件),您会发现有些行没有内容。这就是为什么您会遇到问题的原因。如果您不想要点,则注释掉命令plt.scatter(x,y,c=z,s=20)
。我用它来检查轮廓是否正确。我会写一些关于您的代码的东西,只需要更多时间。 - ahelm