Fundamentals 9 min read

Creating Dynamic Charts in Python with Matplotlib FuncAnimation

This tutorial explains how to generate animated line, bar, and pie charts in Python using Matplotlib's FuncAnimation, covering required imports, data preparation, key parameters, example code snippets, and how to save the resulting animations as GIF files.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Creating Dynamic Charts in Python with Matplotlib FuncAnimation

In the era of massive data, analysts need to convey insights clearly, and animated visualizations are an effective way to do so. This article demonstrates a simple method for creating dynamic charts in Python using Matplotlib's FuncAnimation class.

Matplotlib is a widely used open‑source plotting library for Python. Its FuncAnimation extension allows static figures to be turned into animations by repeatedly redrawing the canvas.

How FuncAnimation works

The animation starts with two lines of code:

<code>import matplotlib.animation as ani
animator = ani.FuncAnimation(fig, chartfunc, interval=100)</code>

The main arguments are:

fig : the Figure object that holds the plot.

chartfunc : a function that receives a frame index and updates the plot.

interval : delay between frames in milliseconds (default 200 ms).

After defining a function that draws the chart for a given frame, FuncAnimation repeatedly calls it, creating the animation.

Data preparation

<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 drop unnecessary columns
df_interest = df.loc[
    df['Country/Region'].isin(['United Kingdom', 'US', 'Italy', 'Germany']) &
    df['Province/State'].isna()
]
# Transpose and clean the DataFrame
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

First set up the figure and static styling, then define a function that draws the line up to the current frame and let FuncAnimation animate it.

<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>

The update function:

<code>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()
</code>

Animated pie chart

The structure is similar to the line chart, but each frame draws a pie of the cumulative data up to that point.

<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 bar chart can be drawn vertically or horizontally; the example shows both options.

<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>

Saving the animation

After the animation is created, it can be saved to a GIF file with a single line of code:

<code>animator.save(r'C:\temp\myfirstAnimation.gif')
</code>

By following these steps, readers can produce animated visualizations for line, bar, and pie charts, making data stories more engaging and easier to understand.

animationTutorialData VisualizationMatplotlibfuncanimation
Python Programming Learning Circle
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.