Matplotlib动画遍历 pandas 数据框列表 [英] Matplotlib animation iterating over list of pandas dataframes

查看:51
本文介绍了Matplotlib动画遍历 pandas 数据框列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫数据框架列表,每个框架有2列.到目前为止,我有一个函数,当给定索引i时,它将获取对应于索引i的帧,并绘制第一列数据与第二列数据的关系图.

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

我现在的问题是,如何使这个循环遍历帧列表并动画显示每个帧的图形连续 0.3 秒.

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.

我更喜欢使用动画库中的 FuncAnimation 类,它为您完成繁重的工作和优化.

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

推荐答案

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

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

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

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

这篇关于Matplotlib动画遍历 pandas 数据框列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆