Creating Dynamic Charts with Matplotlib's FuncAnimation in Python
This article explains how to use Python's Matplotlib library and its FuncAnimation extension to transform static line, bar, and pie charts into animated visualizations, demonstrating code setup, key parameters, and example implementations with COVID-19 death data.
In an era of massive data growth, the article emphasizes the importance of dynamic data visualization for clearer communication, focusing on Python's Matplotlib library and its FuncAnimation extension.
FuncAnimation, part of Matplotlib's animation module, repeatedly redraws a figure to create motion; its basic inputs are the figure object, an update function, and the frame interval in milliseconds.
Example code to import and instantiate FuncAnimation:
import matplotlib.animation as ani
animator = ani.FuncAnimation(fig, chartfunc, interval=100)Key parameters explained:
fig – the Matplotlib figure to draw on.
chartfunc – a function that receives a frame index and updates the plot.
interval – delay between frames (ms), default 200.
The tutorial loads COVID‑19 death data from a public CSV, filters for several countries, transposes the table, and drops irrelevant columns, preparing a time‑series DataFrame for animation.
import matplotlib.animation as ani
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
url = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv'
df = pd.read_csv(url, delimiter=',', header='infer')
# filter and reshape
df_interest = df.loc[df['Country/Region'].isin(['United Kingdom','US','Italy','Germany']) & df['Province/State'].isna()]
# further processing omitted for brevityDynamic line chart – set up figure, axis labels, and a function that plots data up to the current frame, then call FuncAnimation.
import numpy as np
import matplotlib.pyplot as plt
color = ['red','green','blue','orange']
fig = plt.figure()
plt.xticks(rotation=45, ha='right', rotation_mode='anchor')
plt.subplots_adjust(bottom=0.2, top=0.9)
plt.ylabel('No of Deaths')
plt.xlabel('Dates')
def buildmebarchart(i=int):
plt.legend(df1.columns)
p = plt.plot(df1[:i].index, df1[:i].values)
for i in range(0,4):
p[i].set_color(color[i])
animator = ani.FuncAnimation(fig, buildmebarchart, interval=100)
plt.show()Dynamic pie chart – similar structure but uses ax.clear() and plot.pie with an autopct function to display absolute values.
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
explode = [0.01,0.01,0.01,0.01]
def getmepie(i):
def absolute_value(val):
a = np.round(val/100.*df1.head(i).max().sum(),0)
return int(a)
ax.clear()
plot = df1.head(i).max().plot.pie(y=df1.columns, autopct=absolute_value, label='', explode=explode, shadow=True)
plot.set_title('Total Number of Deaths\n' + str(df1.index[min(i, len(df1.index)-1)].strftime('%y-%m-%d')), fontsize=12)
animator = ani.FuncAnimation(fig, getmepie, interval=200)
plt.show()Dynamic bar chart – supports vertical or horizontal orientation; the update function selects the appropriate Matplotlib bar function based on a variable.
fig = plt.figure()
bar = ''
def buildmebarchart(i=int):
iv = min(i, len(df1.index)-1)
objects = df1.max().index
y_pos = np.arange(len(objects))
performance = df1.iloc[[iv]].values.tolist()[0]
if bar == 'vertical':
plt.bar(y_pos, performance, align='center', color=['red','green','blue','orange'])
plt.xticks(y_pos, objects)
plt.ylabel('Deaths')
plt.xlabel('Countries')
plt.title('Deaths per Country \n' + str(df1.index[iv].strftime('%y-%m-%d')))
else:
plt.barh(y_pos, performance, align='center', color=['red','green','blue','orange'])
plt.yticks(y_pos, objects)
plt.xlabel('Deaths')
plt.ylabel('Countries')
animator = ani.FuncAnimation(fig, buildmebarchart, interval=100)
plt.show()After creating the animations, they can be saved as GIF files with a simple save command.
animator.save(r'C:\temp\myfirstAnimation.gif')The article concludes with a link to the official Matplotlib animation API documentation for readers who want deeper details.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.