Home > database >  Animated graphs in pandas
Animated graphs in pandas

Time:11-17

I have a 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  

I want to plot a animated graph which will animated based on dates, teams, runs (addition of runs for teams)

note : probably I would like to create animated graphs like enter image description here

CodePudding user response:

I created an animation using the pandas_alive mentioned in the question. I'm using an extension of your sample data, which I can't post due to the large gif image size, but you can try running it in your own environment.

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.head()
name    team A  team B  team C  team E  team F
date                    
2020-05-31  125.0   NaN     NaN     NaN     NaN
2020-06-30  NaN     NaN     NaN     98.0    NaN
2020-07-31  NaN     NaN     NaN     125.0   NaN
2020-08-31  NaN     NaN     NaN     75.0    NaN
2020-09-30  NaN     NaN     NaN     126.0   NaN

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)

enter image description here

  • Related