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:
The Integrated Development Environment environments:
- Visual Studio Code
- Anaconda environment
- 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())
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())
- First, import the libraries.
- Then we declare two empty lists x and y.
- Then run a for loop and using the
randint()method fill the lists with some random integers. Remember to set a limit range in the loop.
- Then we call the scatter() function from the
pyplotmodule. Set the plot color to green.
- The last one is very important. We use the
plt.pause()function to set a time gap of 0.01 seconds per plot.
- 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())
- All the process is the same as in the above plot.
- 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.
- ArtistAnimation: Uses artist properties to animate.
- 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:
- func: A function to update each frame on the screen.
- init_func: an initializer for reading the data for plotting.
- frames: to update the nature of each frame per second on hte screen.
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()
- In the first line import the FuncAnimation function from matplotlib’s animation class.
- Then for sub plotting create two objects fig, axs.
- Declare two empty lists as xdata, ydata.
- Then create an instance of plt.plot() function “ln” and “,”. Remember to give a comma as it will create two instances.
- The empty instance helps us to return a sequence of artist objects.
- 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.
- 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.
- Fix the information using set_data() function and insert the two lists xdata and ydata. Return ln and the empty instance.
- Create an animation object for FuncAnimation() class. This takes two functions as parameters.
- initializer function: init() in our code.
- update: update() in our code.
- At last show the graph using plt.show() method.
- We have a beautiful sin(x) function that shows its flow through the axes.
Applications of live plots
- In the stock market, the investors are able to see the live growth and fall of the stock prices.
- Multispeciality hospitals have Heart Monitors that show the pulse rate of patients using animated plots.
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.