Creating Dynamic Charts in Python with Matplotlib FuncAnimation
This tutorial explains how to generate animated line, pie, and bar charts in Python using Matplotlib's FuncAnimation, covering required imports, data preparation, chart configuration, animation loops, and saving the resulting GIFs for effective data visualization.
When reading technical blogs, many authors use animated charts to convey data more intuitively; this article shows a straightforward way to create such animations in Python with Matplotlib.
Matplotlib is a widely used open‑source plotting library, and its FuncAnimation class (part of matplotlib.animation ) can turn static figures into dynamic ones by repeatedly redrawing the canvas.
Basic usage starts with two lines of code:
<code>import matplotlib.animation as ani
animator = ani.FuncAnimation(fig, chartfunc, interval = 100)</code>The function chartfunc is called for each frame; the interval argument sets the delay between frames in milliseconds.
Data preparation – the example loads COVID‑19 death data, filters a few countries, removes unnecessary columns, drops rows with all zeros, and converts the index to dates:
<code>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')
df_interest = df.loc[
df['Country/Region'].isin(['United Kingdom','US','Italy','Germany']) &
df['Province/State'].isna()]
df_interest.rename(index=lambda x: df_interest.at[x, 'Country/Region'], inplace=True)
df1 = df_interest.transpose()
df1 = df1.drop(['Province/State','Country/Region','Lat','Long'])
df1 = df1.loc[(df1 != 0).any(1)]
df1.index = pd.to_datetime(df1.index)</code>Animated line chart – after setting figure aesthetics, a function updates the plot up to the current frame index:
<code>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')</code> <code>def buildmebarchart(i=int):
plt.legend(df1.columns)
p = plt.plot(df1[:i].index, df1[:i].values) # only data up to i
for i in range(0,4):
p[i].set_color(color[i])
animator = ani.FuncAnimation(fig, buildmebarchart, interval = 100)
plt.show()</code>Animated pie chart – the structure is similar, but each frame recomputes a pie slice based on the latest cumulative values:
<code>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)
import matplotlib.animation as ani
animator = ani.FuncAnimation(fig, getmepie, interval = 200)
plt.show()</code>Animated bar chart – the code demonstrates both vertical and horizontal orientations, selecting the appropriate Matplotlib bar function based on a variable:
<code>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()</code>Finally, the animation can be saved as a GIF file with a single command:
<code>animator.save(r'C:\temp\myfirstAnimation.gif')</code>These examples demonstrate that creating dynamic visualizations in Python is accessible with only a few lines of code, making it easier for data scientists and analysts to present time‑series information interactively.
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.