Animations with matplotlib - 2: Random walks
January 31, 2021
This post is the second in a series on how to use the matplotlib.animation
module to create animated plots. The examples here use this module to create animations of 2D random walks.
Introduction #
matplotlib
1 is a python library for creating high quality scientific plots. It contains a module matplotlib.animation
to create animations. This post shows examples of using this module to create some interesting visualizations of 2D random walks.
Random walks #
Random walks2 are models for many physical phenomena, such as the movement of molecules in a liquid or gas, and the diffusion of proteins on the cell membrane. To simulate a random walk, a particle is placed at some initial position $\bold{r}_0 = (x_0, y_0)$ and advanced using the recursion relation:
$$ \bold{r}_{j+1} = (x_j + \delta x, y_j + \delta y) $$
The displacement along each axis is a normally distributed random variable: $$ \delta x, \delta y \sim \cal{N}(0, \sigma) $$
This algorithm produces a Gaussian random walk. The standard deviation $\sigma$ of the normal distribution is related to the diffusion coefficient of the particle3.
In the examples below, particles are initially placed within a small central region of the simulation domain. Each particle moves independently, following the random walk algorithm above. Over time, the aggregated random motion of the particles disperses them like a drop of ink mixing in water.
Examples #
These examples follow a common template:
- Set up an empty plot
- Initialize with plot elements, eg: points in their initial location
- Update plot element attributes, eg: change point coordinates
Step 3 is repeated at each frame to advance the animation. The function FuncAnimation()
implements these steps.
First, Load the needed libraries
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.animation as anim
from IPython.display import HTML
from pathlib import Path
Example 1: Diffusing particles #
The first simulation shows the position of particles over time. In the next code block, init()
plots the particles in their initial position, move()
updates particle positions using the random walk algorithm above, and FuncAnimation()
uses these functions as inputs to generate the animation:
|
|
The resulting output shows how particles diffuse and disperse away from their initial locations.
Example 2: Particle tracks #
The next example plots the trajectory of each particle. To do this efficiently, first simulate the entire trajectory for each particle, and store all trajectories in a numpy
array:
|
|
Then plot the trajectories by showing the progress up to each frame. Note how the function set_markevery()
is used to display both the marker and the line for each track.
|
|
The output shows how diffusing particles explore space:
Example 3: Particle trails #
In this example, the animaiton shows a “trail” behind each particle rather than the complete trajectory. The maximum trail length can be changed in the move()
function below.
|
|
which produces the following output
Summary and references #
These examples demonstrate how the matplotlib.animation
module can be used to create dynamic visualizations. The complete code for this post is available in this jupyter notebook
References:
- https://matplotlib.org/3.3.3/api/animation_api.html
- https://towardsdatascience.com/animations-with-matplotlib-d96375c5442c
- https://brushingupscience.com/2016/06/21/matplotlib-animations-the-easy-way/
- https://brushingupscience.com/2019/08/01/elaborate-matplotlib-animations/
- Download Jupyter notebook with code
-
$\sigma = \sqrt{2Dt}$ where $D$ is the diffusion coefficient, and $t$ is the time interval between observation ↩︎