【发布时间】:2015-01-31 18:39:51
【问题描述】:
我一直在尝试使用 PolyCollection 制作一个与此非常相似的图表: http://matplotlib.org/examples/mplot3d/polys3d_demo.html
不同之处在于,我希望我的代码从文件夹中读取所有 CSV 文件并在其中绘制数据(不是随机数)。每个 CSV 文件都包含一个光谱,即两列和一定数量的行。我希望第一行是我的 x 值,第二行是相应的 z 值。
我试过了:
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
fig=plt.figure()
ax = fig.gca(projection='3d')
input_path = 'input'
spectrumfiles = []
verts=[]
for root, dirs, files in os.walk(input_path):
for name in files:
if os.path.splitext(name)[1] == '.CSV' or os.path.splitext(name)[1] == '.csv':
spectrumfiles.append(os.path.join(root,name))
zs = np.arange(len(files))
for name in spectrumfiles:
spectrum = np.loadtxt(name, delimiter=',')
#xs = spectrum[:,0] #I tried this first but then realised that "spectrum
#ys = spectrum[:,1] #already has the needed shape
#verts.append(list(zip(xs,ys)))
verts.append(spectrum)
poly = PolyCollection(verts, facecolors=np.ones(len(verts))) #I'm not too bothered with
poly.set_alpha(0.7) #colours at the moment
ax.add_collection3d(poly, zs=zs, zdir='y')
plt.show()
现在,我得到的图表是空的。
编辑: 这里有4个样本FILES
编辑2: 这里有一些关于stackoverflow的相关问题的链接。 - Matplotlib plot pulse propagation in 3d - Waterfall plot python?
【问题讨论】:
-
这里似乎有几个关于 PolyCollection 的问题。但我也无能为力。我将它们添加到我原来的问题中。
-
verts的形状是什么?此外,您的数据中是否有任何 NaN 或其他不良数据?那样会搞砸的。 -
shape(verts) 返回 (4L, 3449L, 2L),所以这是 4 个光谱,每个光谱有 3499 行和 2 列。那里没有 NaN,使用 matplotlib.pyplot.plot 单独绘制每个光谱就可以了。
-
当我拿走你的代码并用随机数(例如
spectrum = np.random.rand(100,2))替换文件读取时,它工作正常。我会看看你的阅读效果。
标签: python csv matplotlib