How to use matplotlib.animation in Python
In this article, we will see how to use matplotlib.animation in Python. Let’s create a realtime animation using the animation features of matplotlib which can then be saved as a video as well. If you don’t have matplotlib installed already, install it using the following command.
pip install matplotlib
Use matplotlib.animation in Python
If you know to plot a graph using matplotlib, it is similar to that except that we need to plot repeatedly at specified intervals. The FuncAnimation method helps us to animate the plotting.
First, let create a subplot as we do while plotting a regular graph. The following code is used to animate the squares of numbers. The code is as follows:
import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation x_data =  y_data =  fig, ax = plt.subplots() ax.set_xlim(0, 10) ax.set_ylim(0, 100) line, = ax.plot(1, 1) def animate(i): x_data.append(i) y_data.append(i ** 2) line.set_xdata(x_data) line.set_ydata(y_data) return line, animation = FuncAnimation(fig, animate, frames=np.arange(0, 11, 1), interval=10) plt.show()
The x_data and y_data are two lists that store the values that are to be plotted. The subplots are created and the x and y limits are set although this is optional. Then the initial values are plotted.
The animate function is used to add additional values to the plot. The values must be set and returned every time to indicate the changed values.
The FuncAnimation takes the figure object, update function, frames, interval between the plotting, number of frames, blit etc. as arguments. The blit is important as this indicates whether the changed values must be plotted or the entire values are to be changed, which can make the animation render faster.
The animation can then be viewed by plt.show() or can be saved as a video file by the method save(filename) of the object returned by the FuncAnimation().
To save the animation, add the following code to the end of the above code.
In order for this to work, you need FFmpeg installed on your computer which is similar to a driver for multimedia files. If you don’t have FFmpeg installed, you can download it from here.
I hope you found this article useful in understanding how to make animations in matplotlib in Python.