Simulating and Visualizing a Random Walk in Python

Introduction: What Is a Random Walk?

A random walk is a mathematical process that describes a path made up of a sequence of random steps.
Imagine flipping a coin — if it’s heads, you step forward; if it’s tails, you step backward.
Repeat this hundreds of times, and you’ll have what’s known as a 1D random walk.

Random walks appear everywhere in science:

  • Biology: modeling molecule diffusion and cell movement
  • Finance: stock price fluctuations
  • Physics & Meteorology: Brownian motion, pollutant transport, and atmospheric turbulence

Although each walk is unpredictable, when we look at many random walks together, patterns emerge — like how the average distance from the start increases with the square root of the number of steps.

A Simple 1D Random Walk

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Lets start with the simplest case  moving left or right randomly.

import numpy as np
import matplotlib.pyplot as plt

# Number of steps
n_steps = 500

# Randomly choose steps: +1 (right) or -1 (left)
steps = np.random.choice([-1, 1], size=n_steps)

# Compute position after each step
position = np.cumsum(steps)

# Plot the walk
plt.figure(figsize=(10, 5))
plt.plot(position, lw=2, color='royalblue')
plt.axhline(0, color='black', lw=1, linestyle='--')
plt.title("1D Random Walk Simulation", fontsize=16)
plt.xlabel("Step Number")
plt.ylabel("Position")
plt.grid(True, alpha=0.3)
plt.show()

Explanation:

  • Each step is independent of the previous one.
  • Over time, the walker’s position “wanders” around zero.
  • On average, the distance from the start grows with ( \sqrt{N} ), where ( N ) is the number of steps.

Simulating and Visualizing a Random Walk in Python
Simulating and Visualizing a Random Walk in Python

Moving to 2D

Now let’s extend the idea to two dimensions — where each step has a random direction.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import numpy as np
import matplotlib.pyplot as plt

n_steps = 1000

# Random angles for each step (in radians)
angles = np.random.uniform(0, 2 * np.pi, n_steps)
x_steps = np.cos(angles)
y_steps = np.sin(angles)

# Compute positions
x = np.cumsum(x_steps)
y = np.cumsum(y_steps)

# Plot the path
plt.figure(figsize=(6, 6))
plt.plot(x, y, lw=1.5, color='royalblue')
plt.scatter(0, 0, color='green', label='Start', zorder=3)
plt.scatter(x[-1], y[-1], color='red', label='End', zorder=3)
plt.title("2D Random Walk", fontsize=16)
plt.xlabel("X position")
plt.ylabel("Y position")
plt.legend()
plt.axis("equal")
plt.grid(alpha=0.3)
plt.show()

Interpretation:

  • Each step has a fixed length but a random direction.
  • The trajectory represents how particles diffuse randomly over a surface.
  • The spread (variance) increases with the number of steps.

Simulating and Visualizing a Random Walk in Python
Simulating and Visualizing a Random Walk in Python

Multiple Walkers — Ensemble Statistics

A single walk is noisy. Let’s simulate multiple walkers to reveal statistical behavior.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import numpy as np
import matplotlib.pyplot as plt

n_walkers = 30
n_steps = 200

plt.figure(figsize=(8, 6))

for i in range(n_walkers):
    steps = np.random.choice([-1, 1], size=n_steps)
    position = np.cumsum(steps)
    plt.plot(position, alpha=0.5)

plt.title("Ensemble of 1D Random Walks")
plt.xlabel("Step Number")
plt.ylabel("Position")
plt.grid(alpha=0.3)
plt.show()

Observation:

  • The mean position remains near zero.
  • The spread (variance) grows with the number of steps — a hallmark of diffusion.

Simulating and Visualizing a Random Walk in Python
Simulating and Visualizing a Random Walk in Python

Animated 2D Random Walk (Matplotlib)

Animations bring random walks to life! Let’s show the path evolving over time.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from IPython.display import HTML

# Parameters
n_steps = 300
step_size = 1

# Initialize positions
x = np.zeros(n_steps)
y = np.zeros(n_steps)

# Random directions for steps (n_steps-1 increments)
angles = np.random.uniform(0, 2*np.pi, n_steps-1)
x[1:] = np.cumsum(np.cos(angles) * step_size)
y[1:] = np.cumsum(np.sin(angles) * step_size)

# Create figure
fig, ax = plt.subplots(figsize=(6,6))
line, = ax.plot(x[:1], y[:1], lw=2, color='royalblue')  # first point
point, = ax.plot([x[0]], [y[0]], 'ro', markersize=6)    # first point as sequence
ax.set_xlim(x.min()-2, x.max()+2)
ax.set_ylim(y.min()-2, y.max()+2)
ax.set_title("Animated 2D Random Walk")
ax.set_aspect('equal')
ax.grid(True, alpha=0.3)

# Update function
def update(frame):
    line.set_data(x[:frame+1], y[:frame+1])
    point.set_data([x[frame]], [y[frame]])  # <-- must be a sequence
    return line, point

# Create animation
ani = FuncAnimation(fig, update, frames=n_steps, interval=30, blit=True)

# Display in Jupyter notebook
HTML(ani.to_jshtml())

Simulating and Visualizing a Random Walk in Python
Simulating and Visualizing a Random Walk in Python

Interactive Visualization (Plotly)

For presentations or web-based notebooks, Plotly makes it easy to explore the walk interactively.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import numpy as np
import plotly.graph_objects as go

n_steps = 500
angles = np.random.uniform(0, 2 * np.pi, n_steps)
x = np.cumsum(np.cos(angles))
y = np.cumsum(np.sin(angles))

fig = go.Figure()

fig.add_trace(go.Scatter(
    x=x, y=y,
    mode='lines+markers',
    line=dict(color='royalblue'),
    marker=dict(size=4, color='red'),
    name='Random Walk'
))

fig.update_layout(
    title="Interactive 2D Random Walk",
    xaxis_title="X position",
    yaxis_title="Y position",
    width=600, height=600,
    showlegend=False,
    template='plotly_white'
)
fig.update_xaxes(scaleanchor="y", scaleratio=1)
fig.show()

Interactivity adds:

  • Zooming and panning
  • Hover info (coordinates)
  • A clear sense of diffusion symmetry

Simulating and Visualizing a Random Walk in Python
Simulating and Visualizing a Random Walk in Python

Summary

Concept What You Learned
1D Random Walk Basic idea of random motion and cumulative sum
2D Random Walk Extension to spatial diffusion
Multiple Walkers How randomness averages out statistically
Animation Visual intuition of motion and diffusion
Interactivity Exploration and teaching with engagement

Extensions to Try

  1. Biased random walk – add a small drift (e.g., +0.1 each step).
  2. Variable step size – simulate turbulence or Lévy flights.
  3. 3D random walk – great for particle diffusion or atmospheric motion.
  4. Mean square displacement analysis – verify the linear relationship with step count.

Final Thought

Random walks are more than just fun simulations — they’re a cornerstone of probability, physics, and data science.
Whether modeling smoke dispersal, animal movement, or financial markets, random walks reveal how simple rules can create complex behavior.

References

Links Site
https://numpy.org/doc/stable/reference/random/index.html NumPy Random Module (for generating random steps)
https://numpy.org/doc/stable/reference/generated/numpy.cumsum.html NumPy cumsum() for cumulative sums used in random walks
https://matplotlib.org/stable/tutorials/introductory/pyplot.html Matplotlib Pyplot Basics
https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html Matplotlib plot() function documentation
https://matplotlib.org/stable/api/animation_api.html Matplotlib Animation API Reference
https://matplotlib.org/stable/api/_as_gen/matplotlib.animation.FuncAnimation.html Official FuncAnimation documentation
https://ipython.readthedocs.io/en/stable/api/generated/IPython.display.html#IPython.display.HTML IPython HTML() for displaying animations in notebooks
https://jupyter.org/ Jupyter Project Homepage
Image

of