请问我对python的了解很少,但是我试图在3d图形中输出csv文件(csvfile)数据集。到目前为止,我的代码如下:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import csv
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
with open('new3.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
next(readCSV)
next(readCSV)
next(readCSV)
XS =[]
YS =[]
ZS =[]
for column in readCSV:
xs = column[1]
ys = column[2]
zs = column[3]
XS.append(xs)
YS.append(ys)
ZS.append(zs)
ax.scatter(XS, YS, ZS, c='r', marker='o')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
但是我一直想出标题中的错误。感谢您的帮助
答案 0 :(得分:0)
该错误是因为您试图绘制str
类型对象的三个列表。它们必须为float
或类似类型,并且不能隐式转换。您可以通过以下修改来明确地进行类型转换:
for column in readCSV:
xs = float(column[1])
ys = float(column[2])
zs = float(column[3])
还请注意,ax.scatter
应该位于循环 之内
for column in readCSV:
xs = float(column[1])
ys = float(column[2])
zs = float(column[3])
XS.append(xs)
YS.append(ys)
ZS.append(zs)
ax.scatter(XS, YS, ZS, c='r', marker='o')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
否则,您将在.csv
中的每一行中得到一个新的散点图。我隔离了数据的前5行,并进行了修改,将它们绘制成图
答案 1 :(得分:0)
只是为了好玩,使用numpy默认情况下会通过将字符串传递给matplotlib来规避您的原始问题,同时将代码压缩一些。
raw = """
id,gx,gy,gz,ax,ay,az
0,4.47,-33.23,-77,-106,94
1,-129.04,4.48,-33.22,-78,-94,117
2,-129.04,4.49,33.2,-70,-81,138
3,-129.02,4.49,-33.18,-70,-64,157
4,-129.02,4.5,-33.15,-64,-47,165
"""
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from io import StringIO
# read data
csvfile = StringIO(raw)
d = plt.np.loadtxt(csvfile, delimiter=',', skiprows=2, usecols=[1,2,3])
# instead of csvfile just use filename when using the real file
xyz = plt.np.split(d.T, indices_or_sections=len(d.T))
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(*xyz, c='r', marker='o')
ax.set(**{'%slabel'%s: s.upper() + ' Label' for s in 'xyz'})