Animating Data in Python – A Simple Guide

Animating Data In Python

When we hear the term Data Visualization, what actually do we think of? Just for a while we can get an idea of a graph, line plots, scatter plots, etc. But, what if we can create some live plots. These are not the video recordings, it is just pure programming and using some set of libraries. We are able to make beautiful animations of graphs, histograms, deviations, etc.

Intro to libraries and environment setup

The libraries we are going to use are:

  1. Matplotlib
  2. Seaborn
  3. Numpy

The Integrated Development Environment environments:

  1. Visual Studio Code
  2. Anaconda environment
  3. Python version: 3.9.7

Matplotlib’s animation class

Matplotlib is a very famous library that makes plotting quite easier. It is free and open-source as well as the docs provide an easy get to start guide. For animation purposes, it provides a special class namely: “animation”. This class has several functions that meet our requirements of animating any data in Python. We shall see how to use it using a simple code.

One can check the official documentation at: https://matplotlib.org/stable/api/animation_api.html

First, let us see in short the types of graphs we visualize through computing processes.

Still plots in Matplotlib

They are just pictures depicting the flow of data over several points on the axes.

Animated plots in Matplotlib

These actually tell where the points lie by presenting each pixel one by one on the screen. This makes the plot animate itself.

A simple scatter plot vs an animated scatter plot

Code for simple scatter plot:

from matplotlib import pyplot as plt
import random
import sys

x = []
y = []

for i in range(0, 50):
    x.append(random.randint(0, 100))
    y.append(random.randint(0, 100))
        
# plt.xlim(0, 100)
# plt.ylim(0, 100)
plt.xlabel("X-axis")
plt.ylabel("Y-plot")
plt.title("Simple x-y plot")
plt.scatter(x, y, color = "green")
# plt.pause(0.01)
    
sys.exit(plt.show())

Output:

A Simple Scatter Plot

A Simple Scatter Plot

Code for animated scatter plot:

from matplotlib import pyplot as plt
import random
import sys

x = []
y = []

plt.xlabel("X-axis")
plt.ylabel("Y-plot")
plt.title("Simple x-y plot")
for i in range(0, 50):
    x.append(random.randint(0, 100))
    y.append(random.randint(0, 100))
    plt.scatter(x, y, color = "green")
    plt.pause(0.01)
    
sys.exit(plt.show())

Output:

Explanation:

  1. First, import the libraries.
  2. Then we declare two empty lists x and y.
  3. Then run a for loop and using the random module’s randint() method fill the lists with some random integers. Remember to set a limit range in the loop.
  4. Then we call the scatter() function from the pyplot module. Set the plot color to green.
  5. The last one is very important. We use the plt.pause() function to set a time gap of 0.01 seconds per plot.
  6. Then at last use the plt.show() function to show the plots.

Code for animating bar plots

from matplotlib import pyplot as plt
import random
import sys

x = []
y = []

plt.xlabel("X-axis")
plt.ylabel("Y-plot")
plt.title("Simple bar plot")
for i in range(0, 50):
    x.append(random.randint(0, 100))
    y.append(random.randint(0, 100))
    plt.bar(x, y, color = "green")
    plt.pause(0.01)
    
sys.exit(plt.show())

Output:

Explanation:

  1. All the process is the same as in the above plot.
  2. But we call the plt.bar() function to plot animated bar graphs.

Using the matplotlib.animation module

As we come forward, the main focus goes on to the built-in animation class. This can be more fun to learn. There are several elements of this submodule: There are two subclasses that inherit the properties of this class.

  1. ArtistAnimation: Uses artist properties to animate.
  2. FuncAnimation: follows recursion and continuously calls a function to animate the diagrams/plots.

To make the plotting more elaborative we use these classes. For a quick example, we shall see the flow of the sin(x) function using the same concept.

Syntax of FuncAnimation

class FuncAnimation(fig, func, frames=None, init_func=None, fargs=None, save_count=None, *, cache_frame_data=True, **kwargs)

This class has three basic parameters:

  1. func: A function to update each frame on the screen.
  2. init_func: an initializer for reading the data for plotting.
  3. frames: to update the nature of each frame per second on hte screen.

Code:

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

fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'ro')

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,

ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
                    init_func=init, blit=True)
plt.show()

Output:

Explanation:

  1. In the first line import the FuncAnimation function from matplotlib’s animation class.
  2. Then for sub plotting create two objects fig, axs.
  3. Declare two empty lists as xdata, ydata.
  4. Then create an instance of plt.plot() function “ln” and “,”. Remember to give a comma as it will create two instances.
  5. The empty instance helps us to return a sequence of artist objects.
  6. Create an init() function. In that set the x_lim() from 0, to 360 degrees. In NumPy 0 to 2*np.pi. This decides the rotation of our function from one point to another. Set y_lim() from -1 to 1 and at last return the ln and that empty instance.
  7. Then to update each frame on the screen create an update() function. It takes a frame as a parameter. In the xdata list append frame. In the ydata list append np.sin(frame) which is the sine conversion.
  8. Fix the information using set_data() function and insert the two lists xdata and ydata. Return ln and the empty instance.
  9. Create an animation object for FuncAnimation() class. This takes two functions as parameters.
    1. initializer function: init() in our code.
    2. update: update() in our code.
  10. At last show the graph using plt.show() method.
  11. We have a beautiful sin(x) function that shows its flow through the axes.

Applications of live plots

  1. In the stock market, the investors are able to see the live growth and fall of the stock prices.
  2. Multispeciality hospitals have Heart Monitors that show the pulse rate of patients using animated plots.

Conclusion

So, in this way, we can create beautiful visualizations. They have very nice applications and can be useful in many real-life scenarios. Here, we conclude this topic.