Create an Animated GIF Using Python Matplotlib

Introduction 

 
Anyone learning Python or machine learning is definitely aware of the creation of charts using the matplotlib.pyplot module.  In this article, we will see how to animate a sample chart and then save it as a gif file. 
 
Create Animated GIF Using Python Matplotlib
 
The matplotlib package has an animation module. Two classes of these modules will be required, FuncAnimation and PillowWriter. 
  1. import numpy as np  
  2. import matplotlib.pyplot as plt  
  3. from matplotlib.animation import FuncAnimation, PillowWriter  
  4. %matplotlib notebook  
The FuncAnimation takes the following arguments
  1. fig -  The figure object
  2. func - The function to call at each frame
  3. frames - Source of data to be passed to the function
  4. init_func - A function used to draw a clear frame
%matplotlib notebook  - magic command  - will make our plots interactive within the notebook
 
To begin, we will initialize empty objects as shown below
  1. fig, ax = plt.subplots()  
  2. x, ysin, ycos = [], [], []  
  3. ln1, = plt.plot([], [], 'ro')  
  4. ln2, = plt.plot([], [], 'm*')  
Please note that the call to plt.plot([],[], 'ro') returns a tuple with one element. This is unpacked into a variable ln1. To unpack single item tuples, this convention is followed. If you print the type of ln1 and ln2, you will get a Line2D object.
 
Lets define the init and update functions as shown below:
  1. def init():  
  2.     ax.set_xlim(02*np.pi)  
  3.     ax.set_ylim(-11)  
  4.   
  5. def update(i):  
  6.     x.append(i)  
  7.     ysin.append(np.sin(i))  
  8.     ycos.append(np.cos(i))  
  9.     ln1.set_data(x, ysin)  
  10.     ln2.set_data(x, ycos)  
As can be seen from code, in init function we set our x and y axis limits. In the update function, the arrays x, ysin and ycos are appended with respective values and functions.
 
A Line2D object has set_data function in which you can pass the x values and y values. Now it's time to call our main animation function.
  1. ani = FuncAnimation(fig, update, np.linspace(02*np.pi, 64), init_func=init)  
  2. plt.show()
For the value of frames, I am passing an iterable with 64 values between 0 and 6.28 and that it. Run the code and enjoy the animation.
 
Once you are happy with your animation, you can convert this to a gif by inserting the following command once before the plt.show()
 
Later you can comment them out.
  1. writer = PillowWriter(fps=25)  
  2. ani.save("demo_sine.gif", writer=writer)  
Here, fps is frames per second. I hope you enjoy creating more animated charts of different types.


Similar Articles