Simulating Random Walk in 2D with Matplotlib

  • Share this:

Code introduction


This function simulates a random walk on a 2D plane and plots the path using the matplotlib library.


Technology Stack : The packages and technologies used in this code[English]

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def random_walk(num_steps, start_point):
    import random
    import matplotlib.pyplot as plt

    x = [start_point]
    y = [start_point]

    for _ in range(num_steps):
        dx, dy = random.choice([(1, 0), (-1, 0), (0, 1), (0, -1)])
        x.append(x[-1] + dx)
        y.append(y[-1] + dy)

    plt.figure(figsize=(10, 10))
    plt.plot(x, y, marker='o')
    plt.title("Random Walk")
    plt.xlabel("X-axis")
    plt.ylabel("Y-axis")
    plt.grid(True)
    plt.show()