Fundamentals 9 min read

Creating Simple Animated Charts in Python with Matplotlib FuncAnimation

This article explains how to use Python's Matplotlib library and its FuncAnimation feature to build dynamic line, pie, and bar charts—demonstrated with COVID‑19 death data—while covering essential parameters, code examples, and methods for saving the animations.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Creating Simple Animated 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 guide shows a straightforward method for creating dynamic charts in Python using Matplotlib's FuncAnimation.

Matplotlib is a widely used open‑source plotting library that can generate static charts such as histograms, scatter plots, and more. Its FuncAnimation class enables these charts to animate by repeatedly redrawing the figure. The key inputs for FuncAnimation are:

fig : the Figure object that holds the plot.

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

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

First, the article loads COVID‑19 death data from a public CSV, filters for several countries, and reshapes the DataFrame so that dates become the index. The prepared data ( df1 ) is used as the source for all three animation examples.

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

Animated Line Chart

The line chart example sets up a figure, rotates x‑axis labels, adjusts margins, and defines axis labels. The buildmebarchart function plots the data up to the current frame i and assigns colors to each line.

<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 pie chart uses df1.head(i).max().plot.pie to display the cumulative deaths at each frame, with a custom absolute_value function to format percentages.

<code>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)
animator = ani.FuncAnimation(fig, getmepie, interval = 200)
plt.show()</code>

Animated Bar Chart

The bar chart example can produce either vertical or horizontal bars based on a bar variable. It computes the current index, extracts values, and updates the plot for each frame.

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

After creating an animation, it can be saved to a GIF file with a single line of code:

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

The article concludes with links to additional Python resources and a QR code for a free Python course.

animationpythondata-visualizationMatplotlibpandasNumPyfuncanimation
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.