Methods to create animations in Python

Want to generate animations using in Python? Matplotlib offers good methods to generate and save animations. This post is dedicated for making animations using different methods. According to one's requirement, one may choose a method.

Method 1: using for loop:

Using for loop is a simple and effective method to generate animations. Each iteration updates the frame.

Pros: Simplicity , no separate packages needed

Cons: Can't save the animation

I'm gonna explain with an example of generation of sine wave
link for the code: graph.py

import numpy as np            #numpy for Sine function
import matplotlib.pyplot as plt    #matplotlib for plotting functions
x=np.linspace(0, 2*np.pi,1000)
fig = plt.figure()       
ax = fig.add_subplot(111)
for t in range(0,500):   #looping statement;declare the total number of frames
 y=np.sin(x-0.2*t)       # traveling Sine wave
 ax.clear()
 ax.plot(x,y)
 plt.pause(0.1)

Method 2: Using Animation package: 

Matplotlib is bundled with animation package. Its powerful and provides a variety of functions including choosing frame rate, bit rate, save option, etc. But you need to install FFmpeg in order to use all features of this package.

Pros: Powerful tools
Cons: separate functions need to be written and extra packages should be installed
link for the code: animation.py
Add the required repository. In your terminal type the following:

sudo add-apt-repository ppa:jon-severinsson/ffmpeg

and update

sudo apt-get update

Install the package.

 sudo apt-get install ffmpeg

Making the animation using this method is done in two steps:
Step 1: Define init function and declare the variables

 
def init():
    line.set_ydata(np.ma.array(x, mask=True))
    plt.title("Plot of a travelling sine wave")
    plt.xlabel("x")
    plt.ylabel("y")
    time_text.set_text('')
    return line ,time_text   #return the variables that will updated in each frame

Step 2: Define the plot in a separate function

def animate(i):                  # 'i' is the number of frames  
    line.set_ydata(np.sin(x-0.2*i))  # update the data
    time_text.set_text(' frame number = %.1d' % i)  
    return line , time_text

Step 3: Call the function and save it

ani = animation.FuncAnimation(fig, animate, 200,init_func=init, interval=100, blit=True) #200 is the number of frames
plt.show()
ani.save('mymovie.mp4',fps=15) #save command 

Overall code:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()

x = np.arange(0, 2*np.pi, 0.01)        #defining 'x'

line, = ax.plot(x, np.sin(x))        
#text to display the current frame
time_text = ax.text(0.05, 0.95,'',horizontalalignment='left',verticalalignment='top', transform=ax.transAxes)

#Init function ti initialize variables 
def init():
    line.set_ydata(np.ma.array(x, mask=True))
    plt.title("Plot of a travelling sine wave")
    plt.xlabel("x")
    plt.ylabel("y")
    time_text.set_text('')
    return line ,time_text        #return the variables that will updated in each frame
    
def animate(i):                  # 'i' is the number of frames  
    line.set_ydata(np.sin(x-0.2*i))  # update the data
    time_text.set_text(' frame number = %.1d' % i)  
    return line , time_text

ani = animation.FuncAnimation(fig, animate, 200,init_func=init, interval=100, blit=True)
plt.show()
ani.save('mymovie.mp4',fps=15) #save command 

One thought on “Methods to create animations in Python

Leave a Reply

Your email address will not be published. Required fields are marked *