Matplotlib Animation – calling animation from a function

Creating Animation in Matplotlib:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.figure import Figure
import time
def animated_plot():
def data_gen(t=0):
Generator – generating data to plot the graph
cnt = 0
while cnt < 1000:
cnt += 1
t += 1
a = time.localtime() # used to get seconds
yield t, a.tm_sec  # this ‘yield’ will generate two point continuously.
def init():
Initiation – create the base frame upon which the animation takes place.
ax1.set_xlim(0, 10)
del xdata1[:]  # to clear
del ydata1[:] # to clear
line1.set_data(xdata1, ydata1)
return line1,
def run1(data):
To run the animation(draw function)
t1, y1 = data
xmin, xmax = ax1.get_xlim()
if t1 >= xmax:
ax1.set_xlim(xmin, 2*xmax)
line1.set_data(xdata1, ydata1)
return line1,
fig = plt.figure(figsize =(4,1.5))
ax1 = fig.add_subplot(1, 1, 1) #  1×2 mmatrix, 1st subplot
ax1.tick_params(axis=’both’, which=’major’, labelsize=8)
line1, = ax1.plot([], [], lw=2)
xdata1, ydata1 = [], []
animatn = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=1000,repeat=False, init_func=init)
return animatn # must to put return when the animation is calling from a function
Animat=animated_plot() # calling the function. Here ‘Animat’ is must (it just a variable). Otherwise it will return null

Important points to note:

  • Use ‘return’ to return all the values to continue the animation (when you need to call it from a function). Otherwise animation will stop at its first iteration.
  • Call the function with name. ex. ‘Animat=animated_plot()’ not simply ‘animated_plot()’. In the latter case, all the values are collected as garbage values. So it won’t draw anything in the canvas.