Python读取TXT文件绘制三维图的完整代码示例
本文提供使用Python和Matplotlib库读取TXT文件并绘制三维图形(散点图与折线图)的完整代码示例。重点解析了从文件读取字符串数据后转换为整型的必要步骤,解决了常见的类型报错问题,为初学者提供清晰的实现路径。
对于记忆力较弱的学习者,养成勤做笔记的习惯至关重要。
初次接触Python时,若需绘制三维图形,往往需要查阅大量资料,容易让人感到困惑。经过多方尝试与排查,问题最终得以解决。以下直接展示核心代码实现。
#由三个一维坐标画三维散点
#coding:utf-8
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D
x = []
y = []
z = []
f = open("data\\record.txt")
line = f.readline()
while line:
c,d,e = line.split()
x.append(c)
y.append(d)
z.append(e)
line = f.readline()
f.close()
#string型转int型
x = [ int( x ) for x in x if x ]
y = [ int( y ) for y in y if y ]
z = [ int( z ) for z in z if z ]
print x
fig=plt.figure()
ax=Axes3D(fig)
ax.scatter3D(x, y, z)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()
实现过程中的关键步骤是将字符串类型转换为整型。此前因遗漏此步骤,程序持续报错;完成该转换后,问题迎刃而解。
绘制三维折线图的代码实现。
#
coding: utf - 8
from mpl_toolkits.mplot3d
import axes3d
import matplotlib.pyplot as plt
x = []
y = []
z = []
f = open("data\\record.txt")
line = f.readline()
while line:
c, d, e = line.split()
x.append(c)
y.append(d)
z.append(e)
line = f.readline()
f.close()
# string型转int型
x = [int(x) for x in x
if x
]
y = [int(y) for y in y
if y
]
z = [int(z) for z in z
if z
]
# print x
fig = plt.figure()
ax = fig.gca(projection = '3d')
ax.plot(x, y, z)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()
总结。
本文介绍了利用Python读取TXT文件并绘制三维图的简单代码示例,旨在为读者提供实用参考。欢迎感兴趣的朋友查阅本站其他相关专题。如有疏漏之处,欢迎留言指正,感谢支持。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









