2017-04-16 64 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() 

或者,您只能读取新行并追加这些行(如果更新只是添加行)。