我编写了下面的代码,从文件夹中导入大量文件,在将它们绘制成3D图之前进行读取和转换。文件数通常大于30且低于200,但可能会出现异常。每个文件都有5000行,有3个可绘制值。它工作并产生一个漂亮的3D图,但它很慢。我怀疑我已经使一个数组或列表在其内部增长。我特别怀疑第三个循环。我试图使用121个文件来运行它,并且需要大约半个小时来绘制。
每个数据文件都是衍射图,我想要做的事情基本上是这样的: http://www.carbonhagen.com/_/rsrc/1404718703333/abstracts/insitux-raydiffractionsynthesisofgrapheneoxideandreducedgrapheneoxide/M%C3%B8ller%20Storm%20res%20pic.png?height=371&width=522
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.collections import PolyCollection
import glob
import os
file_list = glob.glob(os.path.join(os.getcwd(),'C:\Users\mkch\Python_Scripts\znox_1','*.ras'))
sourcefiles = []
for file_path in file_list: #this forloops reads all files
with open(file_path) as f_input:
sourcefiles.append(f_input.readlines())
现在所有文件都已导入列表sourcefiles
。
data = []
alldata = []
cutdata = []
length = 118#len(sourcefiles)
for i in range(0,length):
l = len(sourcefiles[i])
cdata = sourcefiles[i][320:l-2]
cutdata.append(cdata)
此for循环删除每个文件中的标题和最后两行。
fig = plt.figure()
ax = fig.gca(projection='3d')
verts = []
zs = list(range(length))
print zs
for j in range(length):
lines = cutdata[j][:]
x = []
y = []
z = []
for line in lines:
a, b, c = line.split()[0:3]
x.append(a)
y.append(b)
y[0], y[-1] = 0, 0
verts.append(list(zip(x, y)))
poly = PolyCollection(verts, facecolors=['r', 'g', 'b','y'])
ax.add_collection3d(poly, zs=zs, zdir='y')
这段代码将每一行分成需要绘图的三个值。然后它将数据添加到绘图中。我怀疑上面的代码花了很长时间。
poly.set_alpha(0.7)
ax.set_xlim3d(0, 100)
ax.set_ylabel('Y')
ax.set_ylim3d(-1, 120)
ax.set_zlabel('Z')
ax.set_zlim3d(0, 120000)
plt.xlabel('2$ \theta$')
plt.show()
标准绘图事物。