2017-04-16 48 views
0

我做了這個代碼,繪製基於一些txt文件的數據的圖(其不斷被其他程序更新)pyplot - 與圖形存在問題刷新

k=0 

xs=[] 
ys=[] 


fig=plt.figure() 
ax1=fig.add_subplot(1,1,1) 
def animate(i): 
    a=open("c:/python27/pos/12386.txt","r").read() 
    lines=a.split("\n") #gets the data from each line 

    for line in lines: 
     if len(line)>1: 
      ys.append(int(line[:line.find(".")])) 
      xs.append(len(xs)+1) 

    ax1.clear() 
    ax1.plot(xs,ys,linewidth=1.0) 

ani=animation.FuncAnimation(fig,animate, interval=6000) 
plt.show() 

怎麼過,每6秒後,他重複圖形,每6秒鐘形成一個新實例。

我想我應該跑在循環內的命令清除圖形以前被再次繪製,或情節每一個新點一個接一個。

回答

2

訣竅是,名單xsys總是與整個文本文件擴展。你需要做的是在添加文本文件的內容之前清除它們。

fig=plt.figure() 
ax1=fig.add_subplot(1,1,1) 

def animate(i): 
    a=open("c:/python27/pos/12386.txt","r").read() 
    lines=a.split("\n") #gets the data from each line 
    xs=[] 
    ys=[] 

    for line in lines: 
     if len(line)>1: 
      ys.append(int(line[:line.find(".")])) 
      xs.append(len(xs)+1) 

    ax1.clear() 
    ax1.plot(xs,ys,linewidth=1.0) 

ani=animation.FuncAnimation(fig,animate, interval=6000) 
plt.show() 

或者,您只能讀取新行並追加這些行(如果更新只是添加行)。