Many Ways to Visualize Your Data via Animation
By: Cornellius Yudha Wijaya
Tags: Machine Learning, Education, Data Science, Programming, Python

Matplotlib Animation

Matplotlib is a “grandfather” library of visualization and based on the MATLAB programming language. Many of the visualization libraries developed would be based on this module and I am pretty sure almost everyone who starting their visualization study would start with this module.

In the matplotlib module, there is an API specifically used to create an animation by providing the necessary base classes. There are two classes, which is FuncAnimation and ArtistAnimation . Here, I would introduce the animation created by FuncAnimation class because it is the easiest one.

I would show how this class work by using an example of the stock price animation above. For preparation, we would need the following trinkets:

To save the animation on your system as mp4 or gif, FFmpeg or ImageMagick need to be installed.

or need to be installed. I acquired the stock price data by using the yahoo_historical module. Install the module by using pip or conda.

Now let’s try to create our animation. First, we need to get our stock price data.

import pandas as pd

from yahoo_historical import Fetcher #Acquire our stock price data. Here I choose to take BBCA.JK stock price (BCA Indonesia Bank) from 1 January 2012 until now with 1 day interval. The data would be automatically imported as Pandas DataFrame object BBCA = Fetcher('BBCA.JK', [2012,1,1], interval = '1d').getHistorical() BBCA.head()

BBCA.JK stock price data

Just to make sure that our data did not contain any NaN value we could do a quick check.

BBCA.isna().any()

No NaN value is present, with this data we could preprocess the data. Because we want to create a time-series animation, we need to transform the data into the Datetime object first.

BBCA['Date'] = pd.to_datetime(BBCA['Date'])

I would want to animate the Adj Close price of BBCA.JK overtime so now let’s start with the animation created using FuncAnimation class from matplotlib.

#importing libraries

import matplotlib.pyplot as plt

import matplotlib.animation as animation #Set the figure for the animation framework

fig = plt.figure(figsize = (10,6)) #creating a subplot

ax1 = fig.add_subplot(1,1,1) #Preparing empty list as we want to animate the graph one data at a time rather than all at once

date = []

adjclose = [] #Using FuncAnimation we need to create an animation function which return and/or done a repetitive action def animate(i):

#Append the empty list with the data located at the index i

date.append(BBCA['Date'].loc[i])

adjclose.append(BBCA['Adj Close'].loc[i]) #Clear the subplot each time the animate is called

ax1.clear()



ax1.plot(date, adjclose)

ax1.tick_params(axis = 'x', labelrotation = 90)



ax1.set_xlabel('Date')

ax1.set_ylabel('Price')

ax1.set_title('BBCA Stock graph with matplotlib')

ani = animation.FuncAnimation(fig = fig, func = animate, frames = len(BBCA), interval = 20)

plt.show()

Here I would explain the parameter of FuncAnimation much closely. The important parameters here are:

fig parameter as the framework for the animation

parameter as the framework for the animation func parameter for the animation function to be called for each frame

parameter for the animation function to be called for each frame frames parameter is the source of data to pass into the func parameter and each frame of the animation. If int provided, it would equivalent to the function range(int).

parameter is the source of data to pass into the parameter and each frame of the animation. If int provided, it would equivalent to the function range(int). interval parameter control the interval between each frame in milliseconds

To save the animation into mp4 or gif, just run the following code.

#You could decide wheteher it is gif or mp4 by change the extension name ani.save('bbca_stock.gif', writer='imagemagick')

or if you use a Jupyter Notebook and want to see the animation directly in your notebook, you could run the following code.

from matplotlib import rc

rc('animation', html='html5') ani

That is how simple animation created using the matplotlib module. In the next section, I would introduce other modules that simplify this animation creation process.