Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib animation iterating over list of pandas dataframes

I have a list of pandas DataFrames with 2 columns each. So far I have a function that, when given an index i, it takes the frame corresponding to index i and plots a graph of data from the first column against the data of the second column.

    list = [f0,f1,f2,f3,f4,f5,f6,f7,f8,f9]
    def getGraph(i):
        frame = list[i]
        frame.plot(x = "firstColumn",y = "secondColumn")
        return 0

My question now is, how do I make this iterate over the list of frames and animate the graphs displaying each one for 0.3 seconds in succession.

Preferably, I would like to use the FuncAnimation class in the animation library which does the heavy lifting and optimizations for you.

like image 585
Amadej Kristjan Kocbek Avatar asked Jul 16 '26 06:07

Amadej Kristjan Kocbek


1 Answers

Set animate function and init to axes, figure and line:

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

f0 = pd.DataFrame({'firstColumn': [1,2,3,4,5], 'secondColumn': [1,2,3,4,5]})
f1 = pd.DataFrame({'firstColumn': [5,4,3,2,1], 'secondColumn': [1,2,3,4,5]})
f2 = pd.DataFrame({'firstColumn': [5,4,3.5,2,1], 'secondColumn': [5,4,3,2,1]})

# make a global variable to store dataframes
global mylist
mylist=[f0,f1,f2]

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 5), ylim=(0, 5))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function of dataframes' list
def animate(i):
    line.set_data(mylist[i]['firstColumn'], mylist[i]['secondColumn'])
    return line,

# call the animator, animate every 300 ms
# set number of frames to the length of your list of dataframes
anim = animation.FuncAnimation(fig, animate, frames=len(mylist), init_func=init, interval=300, blit=True)

plt.show()

For more info look for the tutorial: https://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/

like image 117
Serenity Avatar answered Jul 18 '26 19:07

Serenity



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!