Skip to content
Creating Dynamic Charts in Python with Matplotlib FuncAnimation
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

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.

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

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

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

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.

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
' + str(df1.index[min(i, len(df1.index)-1)].strftime('%y-%m-%d')), fontsize=12)
animator = ani.FuncAnimation(fig, getmepie, interval = 200)
plt.show()

Finally, it shows how to save the animation as a GIF file. animator.save(r'C:\temp\myfirstAnimation.gif') Readers are directed to the Matplotlib animation API documentation for further details.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonPandasNumPydata-visualization
Reader feedback

How this landed with the community

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.