David Spira
David Spira

Reputation: 153

pyplot - issue with graphic being refreshed

I made this code that plots a graph based on the data of some txt files (which keep being updated by another program)

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()

how ever, after every 6 seconds, he repeats the graphic, which becomes a pattern with a new instance every 6 seconds.

I guess i should run a command inside the loop to clear the graphic before it gets plotted again, or plot every new point one by one.

Upvotes: 0

Views: 52

Answers (1)

matusko
matusko

Reputation: 3777

The trick is that lists xs and ys are always extended with whole text file. What you need to do is to clear them before adding the contents of the text file.

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()

Or, you could only read the new lines and append those (if the updates are only adding lines).

Upvotes: 2

Related Questions