Matplotlib 动画迭代 pandas 数据帧列表

2024-06-02

我有一个 pandas DataFrame 列表,每个数据框有 2 列。到目前为止,我有一个函数,当给定索引 i 时,它会采用与索引 i 相对应的框架,并根据第二列的数据绘制第一列的数据图。

    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

我现在的问题是,如何使其迭代帧列表并以动画方式连续显示每个帧 0.3 秒。

最好,我想使用动画库中的 FuncAnimation 类,它可以为您完成繁重的工作和优化。


将 animate 函数和 init 设置为坐标轴、图形和线条:

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

有关更多信息,请查找教程:https://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/ https://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Matplotlib 动画迭代 pandas 数据帧列表 的相关文章

随机推荐