我想将我的txt文件放在一个额外的目录或文件夹中。 txt文件是具有3个coloums的数据。然后,我希望从这些文件中绘制一个3D图表。代码以这样的方式编写,我可以随意更改该txt文件而不再更改我的代码。所以代码如下所示:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.mlab import griddata
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np
from os import listdir
def test(datei):
return datei.endswith('.txt')
def xyz_ret(file):
f = open(file, 'r')
xyz = []
for i in f:
ret = i.replace('\n','')
xyz.append(map(float,(ret.split('\t'))))
xyz = np.array(xyz)
return xyz[:,0],xyz[:,1],xyz[:,2]
files=listdir("data")
files=filter(test, files)
files.sort()
x,y,z = xyz_ret(files)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
xi = np.linspace(min(x), max(x))
yi = np.linspace(min(y), max(y))
X, Y = np.meshgrid(xi, yi)
Z = griddata(x, y, z, xi, yi)
surf = ax.plot_surface(X, Y, Z, rstride=6, cstride=6, cmap=cm.jet,
linewidth=0)
ax.set_zlim3d(min(z), max(z))
ax.w_zaxis.set_major_locator(LinearLocator(10))
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
然而,我收到错误:
C:\Users\penang\Desktop\3D drawing\test5>python test5.py
Traceback (most recent call last):
File "test5.py", line 28, in <module>
x,y,z = xyz_ret(files)
File "test5.py", line 13, in xyz_ret
f = open(file, 'r')
TypeError: coercing to Unicode: need string or buffer, list found
有人可以帮忙吗?