Simple Matplotlib Animation Example
In this post, you will learn how to draw simple matplotlib animation.
The Matplotlib has a matplotlib.animation package for creating animations. Matplotlib is a Python 2D plotting library and, furthermore, the most well-known one. The greater part of the individuals start their Data Visualization venture with Matplotlib. One can create plots, histograms, power spectra, bar diagrams, blunder outlines, scatterplots, and so on effectively with matplotlib. This package has an animation base class that deals with animation. These are the two interfaces to achieve this goal-
- FuncAnimation- It creates animations by repeatedly calling a function.
- ArtistAnimation- It creates animations by using a fixed set of artist objects.
Modules Required
The Matplotlib animation program requires you import these necessary modules- matplotlib and numpy.
We may also need to import these modules in case we want to save the animation as mp4 or gif- ffmpeg and imagemagick.
Syntax of FuncAnimation()
FuncAnimation(fig, func, frames=None, init_func=None, fargs=None, save_count=None, cache_frame_data=True)
fig- The figure object that is used to get draw, resize, and any other needed events.
func- The function to call at each frame.
frames- iterable, int, generator function, or None, optional.
init_func- callable, optional. A function used to draw a clear frame.
fargs- tuple or None, optional. The additional arguments to pass to each call to func.
save_count- int, default: 100. The callback for the number of values from frames to cache.
cache_frame_data- bool, optional. Controls whether frame data is cached.
Matplotlib Animation Code Explanation
Here, we will explain the matplotlib animation code line by line. First, we will import the necessary modules -
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
To make a new figure, use plt.figure(). The num attribute is not provided here, so the figure number will be incremented.
plt.figure()
The plt.axes() function adds axes to the current figure, making them the current axes. Here, xlim and ylim set axis limits. The xlim([xmin xmax]) or ylim([ymin ymax]) sets the axis limits in the current axes to the given values.
ax = plt.axes(xlim=(0, 4), ylim=(-2, 2))
Next, we will plot y versus x as lines and/or markers using the ax.plot() method. Here, we pass 'bo' in the third argument to plot x and y using blue circle markers.
ln, = ax.plot([], [], 'bo')
Next, we will create lists to store x and y axis points.
xdata, ydata = [], []
Next, we will create a function to draw a clear frame. The ax.set_xlim() sets the x-axis view limits and the ax.set_ylim sets the y-axis view limits. The numpy np.pi creates a curve.
def init():
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1, 1)
return ln,
Next, we will define a function to call at each frame.
def update(frame):
xdata.append(frame)
ydata.append(np.sin(frame))
ln.set_data(xdata, ydata)
return ln,
Here is the function to create matplotlib animation. We set blit == True to return an iterable of all artists that were modified or created. The frames value np.linspace() returns evenly spaced numbers over a specified interval.
anim = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
init_func=init, blit=True)
Finally, we can save the generated animation as a gif using the imagemagick library. Make sure this is installed on your system. If not, you can download from its official website- https://imagemagick.org/script/download.php
anim.save('animation.gif', writer='imagemagick', fps=60)
Complete Code: Simple Matplotlib Animation Example
Here, we have merged the above code -
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
fig = plt.figure()
ax = plt.axes(xlim=(0, 4), ylim=(-2, 2))
ln, = ax.plot([], [], 'bo')
xdata, ydata = [], []
def init():
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1, 1)
return ln,
def update(frame):
xdata.append(frame)
ydata.append(np.sin(frame))
ln.set_data(xdata, ydata)
return ln,
anim = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
init_func=init, blit=True)
anim.save('animation.gif', writer='imagemagick', fps=60)
The above code returns the following output -
Related Articles
Simple Matplotlib Animation ExampleMatplotlib Pie Chart
Python Line Plot Using Matplotlib
Python Matplotlib 3D Plot
How to save figure in matplotlib pyplot
Python Matplotlib Scatter Plot
Python Pandas Plotting
How to capture a video in Python OpenCV and save
Python OpenCV Overlaying or Blending Two Images
Contour Detection using Python OpenCV
Harris Corner Detection using Python OpenCV
Human Body Detection Program In Python OpenCV
Face Recognition OpenCV Source Code
Canny Edge Detector OpenCV Python
Python NumPy: Overview and Examples
Image processing using Python Pillow
Python OpenCV Histogram Equalization
Python OpenCV Histogram of Color Image
Python OpenCV Histogram of Grayscale Image
Python OpenCV Image Filtering
Python OpenCV ColorMap
Python OpenCV Gaussian Blur Filtering
Python OpenCV Overview and Examples