【问题标题】:Matplotlib animation iterating over list of pandas dataframesMatplotlib 动画迭代熊猫数据帧列表
【发布时间】:2018-01-16 15:17:29
【问题描述】:

我有一个熊猫数据框列表,每列有 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 类,它会为您完成繁重的工作和优化。

【问题讨论】:

    标签: python pandas animation matplotlib


    【解决方案1】:

    将动画函数和初始化设置为轴、图形和线:

    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/

    【讨论】:

      猜你喜欢
      • 2020-07-30
      • 1970-01-01
      • 2018-12-25
      • 2020-05-17
      • 2015-12-09
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多