Python实现读取txt文件并画三维图简单代码示例

yipeiwu_com6年前Python基础

记忆力差的孩子得勤做笔记!

刚接触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() 

最关键的步骤就是那个string类型转int类型,之前缺了这一步,死活的报错,好了,终于搞定!

#画三维线

#
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文件并画三维图简单代码示例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题。如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

pytorch:torch.mm()和torch.matmul()的使用

如下所示: torch.mm(mat1, mat2, out=None) → Tensor torch.matmul(mat1, mat2, out=None) → Tensor...

python用plt画图时,cmp设置方法

在python,有时候是需要画图的,比如把一个矩阵用图像的形式显示,之前用的好好的,每次用plt.imshow(),都是彩色图,不知为啥,突然全是黑白图了,于是需要设置cmap的值,如下...

详解python中docx库的安装过程

详解python中docx库的安装过程

python中docx库的简介 python-docx包,这是一个很强大的包,可以用来创建docx文档,包含段落、分页符、表格、图片、标题、样式等几乎所有的word文档中能常用的功能都包...

详解python中的文件与目录操作

详解python中的文件与目录操作 一 获得当前路径 1、代码1 >>>import os >>>print('Current directo...

Python列表对象实现原理详解

Python列表对象实现原理详解

Python中的列表基于PyListObject实现,列表支持元素的插入、删除、更新操作,因此PyListObject是一个变长对象(列表的长度随着元素的增加和删除而变长和变短),同时它...