Fundamentals 7 min read

Creating Dynamic Charts in Python with Matplotlib FuncAnimation

This article explains how to build animated line, bar, and pie charts in Python using Matplotlib's FuncAnimation library, demonstrating data preparation, key parameters, code examples, and saving 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

The article introduces a simple method for creating animated charts in Python using Matplotlib's FuncAnimation, targeting line, bar, and pie charts with real-world COVID-19 death data.

It explains the required libraries (matplotlib, pandas, numpy) and the key parameters of FuncAnimation (figure, function, interval), and shows how to set up the figure and animation function.

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

For a line chart, it demonstrates setting up the figure, axes labels, and a build function that updates the plot for each frame.

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

Similar code is provided for animated pie and bar charts, highlighting differences such as using df1.head(i).max() for pie slices and choosing vertical or horizontal bars.

<code>def getmepie(i):
    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()</code>

Finally, it shows how to save the animation as a GIF file.

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

Readers are directed to the Matplotlib animation API documentation for further details.

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