simulate and animate random walks in 3d in python

To simulate and animate random walks in 3D using Python, we will use the matplotlib and numpy libraries.

Here is an example code that generates a random walk data in 3D and then animates it using FuncAnimation from matplotlib:

main.py
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
from matplotlib.animation import FuncAnimation

# Generate random walk data
n = 1000 # number of steps
steps = np.random.rand(n, 3) # random steps
steps[steps < 0.5] = -1 # move left/down
steps[steps >= 0.5] = 1 # move right/up
positions = np.cumsum(steps, axis=0)

# Create animation function
fig = plt.figure()
ax = p3.Axes3D(fig)
line, = ax.plot([], [], [], lw=2)

def update(num):
    line.set_data(positions[:num,0], positions[:num,1])
    line.set_3d_properties(positions[:num,2])
    return line,

# Create animation
anim = FuncAnimation(fig, update, frames=n, interval=50, blit=True)

# Show animation
plt.show()
713 chars
28 lines

Here, we first generate random steps using np.random.rand and then apply the rule that if a step is less than 0.5, to move left/down, and if it is greater than or equal to 0.5, to move right/up. We then calculate the positions of each step using np.cumsum and store them in positions.

We then define the update function which updates the line object's data and 3D properties based on the current frame number.

Finally, we create an animation using FuncAnimation and update, and show it using plt.show().

Note that this example code only animates a single random walk. If you want to simulate and animate multiple random walks, you can simply generate additional random walk data and plot them in the same update function.

gistlibby LogSnag