Note
Go to the endto download the full example code.
Animations using Matplotlib#
Based on its plotting functionality, Matplotlib also provides an interface togenerate animations using theanimation module. Ananimation is a sequence of frames where each frame corresponds to a plot on aFigure. This tutorial covers a general guideline onhow to create such animations and the different options available. More information is available in the API description:animation
importmatplotlib.pyplotaspltimportnumpyasnpimportmatplotlib.animationasanimation
Animation classes#
The animation process in Matplotlib can be thought of in 2 different ways:
FuncAnimation: Generate data for firstframe and then modify this data for each frame to create an animated plot.ArtistAnimation: Generate a list (iterable)of artists that will draw in each frame in the animation.
FuncAnimation is more efficient in terms ofspeed and memory as it draws an artist once and then modifies it. On theother handArtistAnimation is flexible as itallows any iterable of artists to be animated in a sequence.
FuncAnimation#
TheFuncAnimation class allows us to create ananimation by passing a function that iteratively modifies the data of a plot.This is achieved by using thesetter methods on variousArtist (examples:Line2D,PathCollection, etc.). A usualFuncAnimation object takes aFigure that we want to animate and a functionfunc that modifies the data plotted on the figure. It uses theframesparameter to determine the length of the animation. Theinterval parameteris used to determine time in milliseconds between drawing of two frames.Animating usingFuncAnimation typically requires these steps:
Plot the initial figure as you would in a static plot. Save all the createdartists, which are returned by the plot functions, in variables so that you canaccess and modify them later in the animation function.
Create an animation function that updates the artists for a given frame.Typically, this calls
set_*methods of the artists.Create a
FuncAnimation, passing theFigureand the animation function.Save or show the animation using one of the following methods:
pyplot.showto show the animation in a windowAnimation.to_html5_videoto create a HTML<video>tagAnimation.to_jshtmlto create HTML code with interactive JavaScript animationcontrolsAnimation.saveto save the animation to a file
The following table shows a few plotting methods, the artists they return and somecommonly usedset_* methods that update the underlying data. While updating datais the most common operation in animations, you can also update other aspects such ascolor or text position.
Plotting method | Artist | Data set methods |
|---|---|---|
| ||
| ||
Covering the set methods for all types of artists is beyond the scope of thistutorial but can be found in their respective documentations. An example ofsuch update methods in use forAxes.scatter andAxes.plot is as follows.
fig,ax=plt.subplots()t=np.linspace(0,3,40)g=-9.81v0=12z=g*t**2/2+v0*tv02=5z2=g*t**2/2+v02*tscat=ax.scatter(t[0],z[0],c="b",s=5,label=f'v0 ={v0} m/s')line2=ax.plot(t[0],z2[0],label=f'v0 ={v02} m/s')[0]ax.set(xlim=(0,3),ylim=(-4,10),xlabel='Time [s]',ylabel='Z [m]')ax.legend()defupdate(frame):# for each frame, update the data stored on each artist.x=t[:frame]y=z[:frame]# update the scatter plot:data=np.stack([x,y]).Tscat.set_offsets(data)# update the line plot:line2.set_xdata(t[:frame])line2.set_ydata(z2[:frame])return(scat,line2)ani=animation.FuncAnimation(fig=fig,func=update,frames=40,interval=30)plt.show()
ArtistAnimation#
ArtistAnimation can be usedto generate animations if there is data stored on various different artists.This list of artists is then converted frame by frame into an animation. Forexample, when we useAxes.barh to plot a bar-chart, it creates a number ofartists for each of the bar and error bars. To update the plot, one wouldneed to update each of the bars from the container individually and redrawthem. Instead,animation.ArtistAnimation can be used to plot each frameindividually and then stitched together to form an animation. A barchart raceis a simple example for this.
fig,ax=plt.subplots()rng=np.random.default_rng(19680801)data=np.array([20,20,20,20])x=np.array([1,2,3,4])artists=[]colors=['tab:blue','tab:red','tab:green','tab:purple']foriinrange(20):data+=rng.integers(low=0,high=10,size=data.shape)container=ax.barh(x,data,color=colors)artists.append(container)ani=animation.ArtistAnimation(fig=fig,artists=artists,interval=400)plt.show()
Animation writers#
Animation objects can be saved to disk using various multimedia writers(ex: Pillow,ffpmeg,imagemagick). Not all video formats are supportedby all writers. There are 4 major types of writers:
PillowWriter- Uses the Pillow library tocreate the animation.HTMLWriter- Used to create JavaScript-basedanimations.Pipe-based writers -
FFMpegWriterandImageMagickWriterare pipe based writers.These writers pipe each frame to the utility (ffmpeg /imagemagick)which then stitches all of them together to create the animation.File-based writers -
FFMpegFileWriterandImageMagickFileWriterare examples offile-based writers. These writers are slower than their pipe-basedalternatives but are more useful for debugging as they save each frame ina file before stitching them together into an animation.
Saving Animations#
Writer | Supported Formats |
|---|---|
.gif, .apng, .webp | |
.htm, .html, .png | |
All formats supported byffmpeg: | |
All formats supported byimagemagick: |
To save animations using any of the writers, we can use theanimation.Animation.save method. It takes thefilename that we want tosave the animation as and thewriter, which is either a string or a writerobject. It also takes anfps argument. This argument is different than theinterval argument thatFuncAnimation orArtistAnimation uses.fps determines the frame rate that thesaved animation uses, whereasinterval determines the frame rate thatthedisplayed animation uses.
Below are a few examples that show how to save an animation with differentwriters.
Pillow writers:
HTML writers:
FFMpegWriter:
Imagemagick writers:
(theextra_args forapng are needed to reduce filesize by ~10x)
Note thatffmpeg andimagemagick need to be separately installed.A cross-platform way to obtainffmpeg is to install theimageio_ffmpegPyPI package, and then to setrcParams["animation.ffmpeg_path"]=imageio_ffmpeg.get_ffmpeg_exe().
Total running time of the script: (0 minutes 7.097 seconds)