gpt4 book ai didi

python - 使用 matplotlib 在 python 中绘制散点图

转载 作者:太空宇宙 更新时间:2023-11-04 04:28:58 25 4
gpt4 key购买 nike

我有一个包含 3000 个点的文件。我必须用这些点绘制一个 3D 散点图。这些点如下,

6.655597594660206395e-01,-5.205175889492101859e-01,4.583497554501108073e-01
3.357418723194116605e-02,-2.482341476533565849e+00,2.009030294705723030e+00
-1.398411818716352728e-01,-1.990250936356241063e+00,2.325394845551588929e+00

有3000个这样的点。

我有代码,它显示错误

TypeError: Cannot cast array data from dtype('float64') to dtype('<U32') according to the rule 'safe'

我写的代码

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

x=[]
y=[]
z=[]

with open('3dpd.out') as f:
lines = f.readlines()
for line in lines :
x.append(line.split(',')[0])
y.append(line.split(',')[1])
z.append(line.split(',')[2])


fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')

ax.set_title("Scatter Plot")
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')


ax.scatter(x, y, z, c='r')

plt.show()

最佳答案

readlines 读取行时,它们被读入为字符串,因此您需要将这些字符串转换为数字。

另请注意,我已将每个步骤分成代码中的不同行(例如,splitfloat 等),这通常有助于调试。 (而且你只需要为每一行调用一次 split。)

这是一个有效的例子:

enter image description here

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

x=[]
y=[]
z=[]

with open('3dpd.out') as f:
lines = f.readlines()
for line in lines :
xs, ys, zs = line.split(',')
xv, yv, zv = [float(v) for v in (xs, ys, zs)]
x.append(xv)
y.append(yv)
z.append(zv)

print type(xs)
print type(xv)

fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')

ax.set_title("Scatter Plot")
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')


ax.scatter(x, y, z, c='r')

plt.show()

关于python - 使用 matplotlib 在 python 中绘制散点图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53021497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com