1
votes

I am trying to dynamically update a matplotlib from a .txt file that periodically updates.

For this, I used the following tutorial.

https://pythonprogramming.net/python-matplotlib-live-updating-graphs/

The .txt file looks like such

1,2
2,3
3,6
4,9
5,4
6,7
7,7
8,4
9,3
10,10

The code looks like such:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time

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

def animate(i):
    pullData = open("sampleText.txt","r").read()
    dataArray = pullData.split('\n')
    xar = []
    yar = []
    for eachLine in dataArray:
        if len(eachLine)>1:
            x,y = eachLine.split(',')
            xar.append(int(x))
            yar.append(int(y))
    ax1.clear()
    ax1.plot(xar,yar)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()

This output a figure with these points plotted.

When I update with a new line, such as 11,15, and save there is no updated figure.

How can I make this update to the current figure as a new line is added to the .txt file?

I have tried some of the solutions to these questions asked on stackoverflow without success:

live updating with matplotlib

What is the currently correct way to dynamically update plots in Jupyter/iPython?

1

1 Answers

1
votes

I created the code with the understanding that the intent of the question was to draw a graph based on the row-by-row data by retrieving the values from an updated, localized text file. The main points that I modified are the initial settings and updating the values in the animation function.

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
from matplotlib.animation import PillowWriter
#from IPython.display import HTML



pullData = open("sampleText.txt","r").read()
dataArray = pullData.split('\n')
frm = len(dataArray) 

fig = plt.figure()
ax1 = plt.axes(xlim=(0, size), ylim=(0, size))

line, = ax1.plot([],[], 'r-', lw=3)
xar = []
yar = []

def animate(i):
    if i < size:
        x,y = dataArray[i].split(',')
        xar.append(int(x))
        yar.append(int(y))
        line.set_data(xar, yar)
        ax1.set_ylim(0, max(yar)+3)
        return line


ani = animation.FuncAnimation(fig, animate, frames=frm, interval=200, repeat=False)
ani.save('plot_ani_test.gif', writer='pillow')
# jupyter lab 
# plt.close()
# HTML(ani.to_html5_video())

enter image description here