2016-09-09 120 views
1

我想繪製一個3D動畫圖形,從file.txt獲取數據。我遇到了一個動畫函數的問題,例如當我在txt文件中引入新的座標時,該圖不會自行更新。代碼如下:從file.txt繪製動畫3d圖形

from mpl_toolkits.mplot3d import axes3d 
import matplotlib.pyplot as plt 
import numpy as np 
import math as m 
import matplotlib.animation as animation 
import time 
np.set_printoptions(threshold=np.inf) 
def animate(i): 
    point_stress=open(r'Prova.txt','r').read() 
    lines=point_stress.split('\n') 
    xs=[] 
    ys=[] 
    zs=[] 
    for line in lines: 
     if len(line)>1: 
     x,y,z=line.split() 
     x=float(x) 
     y=float(y) 
     z=float(z) 
     xs.append(x) 
     ys.append(y) 
     zs.append(z) 
     point_stress.close() 
    ax1.clear() 
    ax1.plot(xs,ys,zs) 
fig=plt.figure() 
ax1=fig.add_subplot(111,projection='3d') 
ani=animation.FuncAnimation(fig,animate,interval=1000) 
ax1.set_xlabel('x') 
ax1.set_ylabel('y') 
ax1.set_zlabel('z') 
plt.show() 
+0

它不反正工作。我想添加座標並同時更新圖形。用你的腳本,需要所有的座標已經寫好。 –

+0

我該怎麼做? –

回答

0
from mpl_toolkits.mplot3d import axes3d 
import matplotlib.pyplot as plt 
import numpy as np 
import matplotlib.animation as animation 

np.set_printoptions(threshold=np.inf) 
fig = plt.figure() 
ax1 = fig.add_subplot(111, projection='3d') 


def init(): 
    global points 
    points = np.loadtxt('Prova.txt') 


def animate(i): 
    ax1.clear() 
    ax1.plot(points[:i, 0], points[:i, 1], points[:i, 2]) 

ani = animation.FuncAnimation(fig, animate, init_func=init, interval=1000) 
ax1.set_xlabel('x') 
ax1.set_ylabel('y') 
ax1.set_zlabel('z') 
plt.show() 

我的txt文件:

1 0 0 
0 1 0 
0 0 1 
1 4 0 
0 1 0 
0 6 1 
1 0 2 
10 1 0 
0 0 1 
1 3 0 
0 1 0 
4 0 1