Easy Matplot animation using less than 15 lines of code

Yogender Pal
2 min readSep 29, 2021

Simply stated, sometimes we need to plot data that is available per second or half a second from some sensors or what not? This comes handy if one is to check the behaviour of data in real-time, for example, room temperature variation. Let's start with the import:

import matplotlib.pyplot as plt
import numpy as np
from celluloid import Camera # getting the camera
import matplotlib.animation as animation
from IPython import display
import time
from IPython.display import HTML

import warnings
%matplotlib notebook
warnings.filterwarnings('ignore')
warnings.simplefilter('ignore')

Celluloid is a Python module published by Jacques Kvam. Celluloid will help in capturing the plotted data in the while loop. First, install Celluloid:

pip install celluloid
  1. Code with while loop to generate data on the fly (to mimic the sensors data so speak)
fig = plt.figure() #Empty fig object
ax = fig.add_subplot() #Empty axis object
camera = Camera(fig) # Camera object to capture the snap

def f(x):
''' function to create a sine wave'''
return np.sin(x) + np.random.normal(scale=0.1, size=len(x))

l = []
while True:
value = np.random.randint(9) #random number generator
l.append(value) # appneds each time number is generated
X = np.linspace(10, len(l)) # creates a line space for x axis
for i in range(10): #plots 10 such lines
plt.plot(X, f(X))
fig.show() #shows the figure object
fig.canvas.draw()
camera.snap() # camera object to capture teh animation
time.sleep(1)

2. Creating and saving the animation object.

animation = camera.animate(interval = 200, repeat = True, repeat_delay = 500)
HTML(animation.to_html5_video())
animation.save('abc.mp4') # to save

That's it. Cheers!!!

--

--

Yogender Pal

I talk about programing, AWS, and two hamsters in my room