Updating Pandas Dataframe from Matplotlib animation function

Viewed 79

I have a simple working Matplotlib animation which increment two lists, xs[] and ys[]:

import matplotlib.animation as animation
import matplotlib.pyplot as plt
import pandas as pd

fig, ax = plt.subplots()
xs = []
ys = []
def animate(i):
    xs.append(i)
    ys.append(i**2)
    ax.clear()
    ax.plot(xs,ys)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()

Now, if I try to use a Pandas DataFrame instead of the lists I get the error:

UnboundLocalError: local variable 'df' referenced before assignment

Using the following code:

fig, ax = plt.subplots()
data = []
df = pd.DataFrame(data,columns=['x','y'])

def animate(i):
    new_row = {'x':i,'y':i**2}
    df = df.append(new_row, ignore_index=True)
    ax.plot(df['x'],df['y'])
ani = animation.FuncAnimation(fig,animate, interval=1000)
plt.show()

How can I update the external Pandas DataFrame from within Matplotlib FuncAnimation without making the DataFrame Global?
Thanks in Advance.

1 Answers

In case anyone is wondering, I ended up declaring a global data[] variable inside my animation function:

def animate(i):
    global data
Related