Animated 3D random walk in Matplotlib

Random walks are mathematical models that depict a walkerthe entity taking steps in a walk's movement through a series of steps. These steps are taken in a random manner, hence the “random” in “random walk”.

The walker’s current position serves as the starting point for each step, and based on a random decision, the walker moves to a new position.

Random steps being taken in a walk
Random steps being taken in a walk

Randomness factor

So the big question is, what do we exactly mean by randomness here?

Well, the randomness in a random walk refers to the uncertainty in determining the direction or the distance of the steps. That means our walker can move in different directions, including forward, backward, left, or right, depending on the settings we’ve applied to the walk.

Note: This exact randomness inherent in random walks is what makes them great for modeling various real-world phenomena that involve uncertainty or stochasticoutcomes that are based on probability boutcomes that are based on probabilityehavior.

Various forms of random walks

Random walks can take on various forms. Let’s discuss two common types:

Simple random walk

Lattice random walk

Only discrete steps are considered in this type of walk. Easily put, the steps in the walk can be in one of the two directions (+1 or -1) with equal probability.

This walk is a little different, and here the steps are taken along the grid or lattice lines.

Some random walk properties

Discrete versus continuous random walks

The walk can either have discrete or continuous steps.

  • Discrete: The walker moves step by step in discrete walks.

  • Continuous: The walker moves smoothly in a continuous space.

Step size distributions and probabilities

The step sizes in random walks can follow different probability distributions, like:

  • Gaussian

  • Uniform

Directional randomness and movement rules

Random walks can also have rules for directional randomness. For instance:

  • Isotropic: Equal probability in all directions.

  • Anisotropic: Direction-dependent probabilities.

Animation walkthrough

Having gone through the core concepts behind random walks, let's now implement a random 3D walk using Python's library Matplotlib.

Importing libraries

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

First and foremost, we import the modules required for this implementation. numpy is used for operations on numbers and matplotlib for plots as well as animations.

Defining distance

distanceOfStep = 0.1

We define distanceOfStep as the maximum distance of each step in our random walk.

walk3DRandom method

def walk3DRandom(stepsPerWalk):
randomStart = np.random.random(3)
generateSteps = np.random.uniform(-distanceOfStep, distanceOfStep, size = (stepsPerWalk, 3))
generateWalk = randomStart + np.cumsum(generateSteps, axis = 0)
return generateWalk

For generating our 3D random walk, we define the walk3DRandom function and pass the number of steps as a parameter.

  • randomStart assigns a random starting position in 3D space using np.random.random(3).

  • generateSteps generates random step sizes within the range of distanceOfStep using np.random.uniform(-distanceOfStep, distanceOfStep, size=(stepsPerWalk, 3)).

  • generateWalk calculates the cumulative sum of the step sizes to obtain the coordinates of the random walk.

  • We return the generateWalk array.

updatePaths method

def updatePaths(frameNum, listOfWalks, listOfLines):
for path, trajectory in zip(listOfLines, listOfWalks):
path.set_data(trajectory[:frameNum, :2].T)
path.set_3d_properties(trajectory[:frameNum, 2])
return listOfLines

For updating the positions of the lines for each frame, updatePaths is defined. We pass frameNum as the current frame number, listOfWalks as the list of random walks, and listOfLines as the list of line objects representing the walks.

  • The for loop iterates over both listOfLines and listOfWalks simultaneously using zip.

  • Inside the loop, we use path to refer to the current line object and trajectory to refer to the current random walk.

  • The line path.set_data(trajectory[:frameNum, :2].T) updates the XX and YY coordinates of the line based on the current frame number. The : operator is the slicing operator.

  • The line path.set_3d_properties(trajectory[:frameNum, 2]) updates the ZZ coordinate of the line based on the current frame number.

  • We finally return the listOfLines, now containing the updated line objects.

Note: The zip method takes iterables as a parameter and then returns iterators for it.

Defining steps and walks

stepsPerWalk = 40
walks = [walk3DRandom(stepsPerWalk) for i in range(50)]

stepsPerWalk represents the number of steps in each random walk. We can customize it according to our needs. On the other hand, walks is a list that generates 50 random walks using the walk3DRandom method we just created above.

Defining figure and subplot

figure = plt.figure()
ax = figure.add_subplot(projection = "3d")

We create a figure and a 3D subplot ax using plt.figure() and figure.add_subplot(projection=“3d”), respectively.

Initializing lines

lines = [ax.plot([], [], [])[0] for _ in walks]

We initialize the lines as empty line objects initially.

Setting up our animation

animationOfWalks = animation.FuncAnimation(
figure, updatePaths, stepsPerWalk, fargs = (walks, lines), interval = 150)

Onto the most exciting part!

To render the animation, we create the animationOfWalks using animation.FuncAnimation. This method takes the figure, the update function updatePaths, the total number of frames stepsPerWalk, and lastly, walks and lines within fargsadditional arguments. We set the interval between the frames as 150 milliseconds (susceptible to change).

Displaying Matplotlib's plot

plt.show()

To see our animation, we use plt.show() to display the animation plot.

Code sample

Having covered the building blocks of our 3D random walk using Matplotlib, let's now join the pieces together and run our code!

The following code will result in an output of our 3D random walk-through GUI. Click on the "run" button to see the output in the "output" tab.

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

distanceOfStep = 0.1

def walk3DRandom(stepsPerWalk):
    randomStart = np.random.random(3)
    generateSteps = np.random.uniform(-distanceOfStep, distanceOfStep, size = (stepsPerWalk, 3))
    generateWalk = randomStart + np.cumsum(generateSteps, axis = 0)
    return generateWalk

def updatePaths(frameNum, listOfWalks, listOfLines):
    for path, trajectory in zip(listOfLines, listOfWalks):
        path.set_data(trajectory[:frameNum, :2].T)
        path.set_3d_properties(trajectory[:frameNum, 2])
    return listOfLines

stepsPerWalk = 40
walks = [walk3DRandom(stepsPerWalk) for i in range(50)]

figure = plt.figure()
ax = figure.add_subplot(projection = "3d")

lines = [ax.plot([], [], [])[0] for _ in walks]

animationOfWalks = animation.FuncAnimation(figure, updatePaths, stepsPerWalk, fargs = (walks, lines), interval = 150)

plt.show()

Walk output

Since our walk will show different steps at different frames and increase slowly, let's observe the output at various times of the animation.

Frame recorded initially
Frame recorded initially
Frame recorded near half-time
Frame recorded near half-time
Frame recorded near the end
Frame recorded near the end

Interesting applications for random walks

  • Physics and chemistry: Simulating particle movements and diffusion in molecular dynamics and understanding the spread of substances or heat in physical systems.

  • Financial modeling: Predicting stock prices and exchange rates based on the unpredictable as well as random nature of market movements.

  • Biology and genetics: Modeling the movement of organisms and particles in biological systems. We could even use this in observing the spreading of genetic traits through populations.

  • Image analysis and computer graphics: Segmenting images into distinct regions and creating animations of objects in computer graphics.

  • Optimization and sampling: Exploring search spaces and finding optimal solutions using random sampling techniques.

  • Random walks in Markov chains: Random walks are pivotal in studying Markov chains. These are basically mathematical models to describe systems that transition between states.

Applications of random walks
Applications of random walks

Food for thought

While the examples discussed earlier focus on 3D random walks, random walks can also be extended to higher dimensions, such as 4D or even higher-dimensional spaces. Higher-dimensional random walks can find applications in physics, finance, and optimization.

Let’s have a pop quiz on our 3D Random Walk!

Q

How does path.set_data(trajectory[:frameNum, :2].T) set both X and Y coordinates in a single statement?

A)

Using the T method.

B)

Using the frame number.

C)

The set_data method takes care of it.

D)

:2 does the slicing to obtain both values.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved