Creating Animated Charts in Python with Matplotlib FuncAnimation
This article introduces a straightforward method for producing animated line, bar, and pie charts in Python using Matplotlib's FuncAnimation, guiding readers through required imports, data preparation, chart parameterization, animation setup, and saving the resulting GIFs.
When reading technical blogs, many authors who explain concepts thoroughly also use animated charts, prompting the question of how those graphics are created and whether the process is difficult.
This article presents a simple way to create animated charts in Python, focusing on line, bar, and pie charts to help data scientists and analysts convey insights more intuitively.
Matplotlib is a widely used open‑source plotting library; its FuncAnimation class (part of the animation module) can turn static figures into animations 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>FuncAnimation requires a figure object, a function that draws the chart for a given frame, and an interval (in milliseconds) between frames.
Before animating, you need to load and preprocess data. The example uses COVID‑19 death counts from a public CSV:
<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')
# Filter for selected countries and clean up
df_interest = df.loc[df['Country/Region'].isin(['United Kingdom','US','Italy','Germany']) & df['Province/State'].isna()]
# Transform data
df1 = df_interest.transpose()
df1 = df1.drop(['Province/State','Country/Region','Lat','Long'], axis=0)
df1 = df1.loc[(df1 != 0).any(1)]
df1.index = pd.to_datetime(df1.index)</code>1. Animated Line Chart
<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')
def buildme_line(i=int):
plt.legend(df1.columns)
p = plt.plot(df1[:i].index, df1[:i].values)
for idx in range(len(p)):
p[idx].set_color(color[idx])
animator = ani.FuncAnimation(fig, buildme_line, interval=100)
plt.show()</code>2. Animated Pie Chart
<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):
ax.clear()
def absolute_value(val):
a = np.round(val/100.*df1.head(i).max().sum(), 0)
return int(a)
plot = df1.head(i).max().plot.pie(y=df1.columns, autopct=absolute_value, 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')))
animator = ani.FuncAnimation(fig, getmepie, interval=200)
plt.show()</code>3. Animated Bar Chart
<code>fig = plt.figure()
bar = ''
def buildme_barchart(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, buildme_barchart, interval=100)
plt.show()</code>After creating the animation, you can save it as a GIF with:
<code>animator.save(r'C:\temp\myfirstAnimation.gif')</code>For more details, consult the official Matplotlib animation API documentation at https://matplotlib.org/3.1.1/api/animation_api.html.
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.