pandas 中的动画图

Animated graphs in pandas

我有一个table,

runs  opposition  date 
10  team A  01 aug 2020
23  team B  13 sep 1975
76  team C  03 Jan 1999 
92  team A  01 aug 1982 
12  team C  01 aug 2020 
100  team B  01 aug 2008 
83  team A  01 aug 2005 
93  team B  01 aug 2006 
23  team B  01 aug 2011 
11  team A  01 aug 2019  

我想绘制一个动画图表,该图表将根据日期、团队、跑步进行动画处理(为团队添加跑步)

注意:可能我想创建像 https://pythonawesome.com/animated-plotting-extension-for-pandas-with-matplotlib/

这样的动画图

我们如何为 table 或 df 绘制这样的动画图?

您可以使用plotly animation

fig = px.scatter(df, x="date", y="runs", animation_frame="opposition")
fig.update_traces(marker_size=40) # increase marker size
fig.write_html("fig.html") # export as html file

这给你(这里只有静态图像...):

我使用问题中提到的 pandas_alive 创建了一个动画。我正在使用您的示例数据的扩展,由于 gif 图像尺寸较大,我无法 post,但您可以在您自己的环境中尝试 运行。

pip install pandas_alive # import 

import pandas as pd
import numpy as np
import random
import pandas_alive

names = ['team A','team B','team C','team E', 'team F']
df = pd.DataFrame({'date': pd.date_range('2020-05-01','2021-11-01', freq='1m'),
                  'name': random.choices(names, k=18),
                  'runs': np.random.randint(0,150,18)})

df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)
df = df.pivot(columns='name')
df.columns = df.columns.droplevel()
df.fillna(0, inplace=True)
df = df.cumsum()

df.head()
name    team A  team B  team C  team E  team F
date                    
2020-05-31  92.0    0.0     0.0     0.0     0.0
2020-06-30  92.0    123.0   0.0     0.0     0.0
2020-07-31  92.0    123.0   0.0     140.0   0.0
2020-08-31  92.0    123.0   0.0     150.0   0.0
2020-09-30  92.0    123.0   0.0     150.0   133.0

def current_total(values):
    total = values.sum()
    s = f'Total : {int(total)}'
    return {'x': .85, 'y': .2, 's': s, 'ha': 'right', 'size': 11}

df.fillna(0).plot_animated('test_animate.gif', period_fmt='%Y-%m', title='Test Bar chart race', period_summary_func=current_total)