Animations Using Python: A Comprehensive Guide
By: Kirthi Tej Yendloori
Tags: Plotly, Matplotlib, Python, Data Visualisation, Animation

A data animation is a program which shows the change in data plots over time. This movement of plots over time is stored as an mpeg video or a gif file. It can be really useful to describe the evolution of something or to visualise impact of time over variables across long duration of time.

Animations can add a sense of time to charts. It is widely used on Panel data and any multivariate data in general to see the change in 2–3 variables over time. Animations, in that sense, increase our capability to visualise more dimensions in data especially time. For example, with animation we can show 5 dimensions in a 2D plot:

X-axis representing variable 1 Y-axis representing variable 2 Point/Line color showing variable 3 Point/Line size/thickness showing variable 4 Animation frames giving a sense of change with variable 5 i.e. time

Data animations can be understood as a sequence of frames of images appearing at a fast speed so that they seem to merge in the same image/frame.

In this blog, we will be sharing our knowledge of animation and will introduce you to animation through python.

Two python animation libraries are discussed in this blog.

Matplotlib Plotly

Data visualization is equal parts of arts and science. Animation is a form of visualization which takes an art-like mindset for designing while science-like mindset for implementing. In Python, Matplotlib and Plotly are popular libraries for creating animations.

Let us first discuss the usage of Matplotlib for creating animations.

Matplotlib

Matplotlib is a library that is used to create 2D plots in a simple and efficient manner. It helps in visualizing high-quality plots and gives easy visual access to any amount of data effortlessly.

We can build a variety of charts and plots like histograms, column charts, pie charts, box plots, scatter plots and much more using matplotlib.

Matplotlib also facilitates animations using its functions.

Some of the pros of matplotlib are

Comprises of a lot of rendering backends. Can reproduce almost just about any plots( with a bit of effort) Has been out there for over a decade, therefore, boasts of a huge user base.

There are areas where matplotlib lags behind

1. Sometimes it has poor stylistic defaults.

2. Often slow for large & complicated data.

3. Poor support for web and interactive graphs.

Animations in matplotlib

Matplotlib’s animation base class deals with the animation part. It provides a framework around which the animation functionality is built. There are two main interfaces primarily used:

FuncAnimation makes an animation by repeatedly calling a function func. ArtistAnimation : Animation using a fixed set of Artist objects.

In this blog, we will be seeing mainly about FuncAnimation tool.

## Prerequisites for animation using matplotlib

1. Modules including numpy and matplotlib should be installed.

2. To save the animation on your system as mp4 we need [ffmpeg] (https://www.ffmpeg.org/) to be installed.

Python itself cannot create animation, it can only create images. Python passes a sequence of image frames into an external animation programme to create a perception of movement i.e. animation.

Depending on what format you decide to use to produce your animation (i.e. mp4 or mpeg) you will also need to install ffmpeg. For this you will have to download and install the appropriate version for your system from https://ffmpeg.org/download.html

Click ffmpeg for step by step installation.

Once you are all set, we can start creating our first basic animation in Jupyter notebook. The code for this animation can be browsed in the following Github repository.

Overall outline for creating an animation:

There are basic steps to consider before starting any animation through python

Import necessary libraries Generate data Define figure,axis and its properties for one frame Create a function to update and create your frames Create animation object Synchronise animation object with plotted figure. Save animation

If you follow the steps above, you are all set for creating an animation in Python. Now let us get our hands dirty with a few example animations.

## Sine Wave Animation

A sine wave or sinusoid is a mathematical curve that describes a smooth periodic oscillation. We will start with the creation of a basic animation of a sine wave moving across the screen. Let’s first see the output and then we shall break down the code to understand what’s going in the code.

In lines(8–10), we define a figure with the axis and its range. Then we create our empty line object which is essentially the one to be modified in the animation. The line object will be populated with data later. In lines(12–15), we create the init function that will make the animation happen. The init function initializes the data and also sets the axis limits. In lines(16–20), we create a function based on our requirement, in our case a sine wave which shifts depending upon the value of i. This function returns a tuple object which tells the animation framework what parts of the plot should be animated. In line 23, we create the actual animation object. This object needs to persist, so it must be assigned to a variable. We’ve chosen a 100 frame animation with a 20ms delay between frames. The time saved with blit=True means that the animations display much more quickly. In lines(27–28), we create prerequisites to save the animation as mp4 video. This requires ffmpeg to be preinstalled in your machine. In line 31, we use save function which converts the animation into mp4 format video. This video will be saved in the corresponding directory you set in your machine.

This is the basic intuition behind creating animations in Matplotlib. With a little tweak in the code, interesting visualisations can be created. Let’s look at a few more next.

## A Particle tracing the path of Simple Harmonic Motion

Simple harmonic motion is typified by the motion of a mass on a spring when it is subject to the linear elastic restoring force given by Hooke’s Law. The motion is sinusoidal in time and demonstrates a single resonant frequency. This animation is similar to the above sine wave with little modification in codes. You can find the codes for the animation in this Github Repository.

Particle movement along SimpleHarmonic Motion

Brownian Motion Animation

Brownian motion is the random 3D motion of fluid particles suspended in a fluid resulting from their collision with the fast-moving molecules in the fluid. The code is quite similar to the sine wave animation in terms of concept.

The changes are introduction of third axis (z-axis) and defining its properties since the plot is in 3 dimensions together with the random nature of motion in all 3 directions.

The code for the Brownian Movement is found in the Github Repository.

3D-Brownian Movement

## Traffic Simulation

This example is an animation of the flow of objects in traffic.This animation idea was inspired from Raindrop animation. You can find the codes to this animation in this Github Repository.

The steps to do this animation are as follows:

Create n random points with a square ‘s’ marker. Initialize the location of these points. Create a categorical variable by using 2 thresholds on x or y coordinate Create a speed variable for all the points and randomly initialise it Inside the animation function, update the position of each point by its speed for each frame Inside the animation function, dissolve the boundaries (by reducing the color intensities) of square markers in each frame to give a perception of continuous flow

Traffic Simulation

## Animation with Plotly:

The Plotly Python graphing library is a scientific graphing library. Graphs can be styled with Python and a GUI, and shared with a URL for others to view, collaborate, or save a copy.

## What is Plotly?

Plotly is one of the finest data visualization tools available built on top of visualization library D3.js, HTML and CSS. It is created using Python and the Django framework. One can choose to create interactive data visualizations online or use the libraries that Plotly offers to create these visualizations in the language/ tool of choice. It is compatible with a number of languages/ tools: R, Python, MATLAB, Perl, Julia, and Arduino.

## Highlights of Plotly:

Using Plotly, interactive plots can easily be shared online with multiple people. Plotly can also be used by people with no technical background for creating interactive plots by uploading the data and using plotly GUI.

The most fascinating feature of Plotly is the interactivity. Plotly is fundamentally different from both matplotlib and seaborn because plots are rendered as static images by both of them while Plotly uses the full power of JavaScript to provide interactive controls like zooming in and panning out of the visual panel. This functionality can also be extended to create powerful dashboards and responsive visualizations that could convey so much more information than a static picture ever could.

Let us discuss in detail about steps to animate using plotly package with an example.

## Point movement around ellipse

In mathematics, an ellipse is a plane curve surrounding two focal points, such that for all points on the curve, the sum of the two distances to the focal points is a constant.

We have plotted an ellipse and animated a point to trace its path.

We are using the numpy’s linspace() function to generate the data. The parametric equation for an ellipse where it is not centred at the origin is x= u+a cos t and y = v+ b sin t where a and b are the radii of x and y-axis respectively.

You can find the python codes for the animation in the Github Repository

In Lines(7–14) we are creating the data required to generate an ellipse. The linspace() function generates a list of numbers having uniform intervals between them with its length equal to the size specified and between the range given. In Lines(16–19) we are specifying the range of the x and y-axis where [xm,ym]is the start of x and y-axis and [xM,yM] is the end of x-axis and y-axis. In Lines(21–23) we are creating the data for the marker which will move around our ellipse by using the same method we used to generate the data for ellipse. In Lines(26,78) we are defining the structure and the appearance of our ellipse and the various functionalities that can be added.We use layout() and frame() function to define animations.

## Panel Data Animation

In statistics and econometrics, panel data or longitudinal data are multi-dimensional data involving measurements over time. In this plotly animation, we have used the popular big-mart retail store data which you can download from this Github Repository. You can also download the dataset from Github Repository.

This animation shows the variation between Item weight and Item MRP over time.The color of the plots denotes the type of the item and size indicates the total outlet sales.

In Lines(4–25 ) we are preprocessing the data before use since it contains missing values and some errors in it. We have used plotly for the above animations, but in this animation, we will be using the plotly.express package since it offers a simpler syntax and helps in rapid generation of figures than plotly which makes the code look lengthy and thereby making it difficult to understand and learn. In Lines(28–37) we are defining our figure appearance and the outcome we are expecting.

## Conclusion:

Animations help to highlight certain features of the visualisation which otherwise cannot be communicated easily with static charts. Every feature in data visualisation should be used judiciously to have the best impact.

Hope this knowledge sharing imparted some confidence and an idea about animations. We urge you to get your hands dirty and create your own animation and obtain meaningful insights from it. Happy learning or should we say Happy Animating!