Search code examples
pythonrandom-walk

Visualizing a 2d random walk in python


I'm trying to make a random walk in 2d, and plot the 2d walk. I've been able to make the walk, but the plot is not exactly what I wanted. Would it be possible to see the walk live in python ? Or just add a label to every point so that you know which point came first and which point came second etc. ?

import numpy as np
import matplotlib.pyplot as plt
import random
def randomWalkb(length):
    steps = []
    x,y = 0,0
    walkx,walky = [x],[y]
    for i in range(length):

        new = random.randint(1,4)
        if new == 1:
            x += 1
        elif new == 2:
            y += 1
        elif new ==3 :
            x += -1
        else :
            y += -1
        walkx.append(x)
        walky.append(y)
    return [walkx,walky]

walk = randomWalkb(25)
print walk
plt.plot(walk[0],walk[1],'b+', label= 'Random walk')
plt.axis([-10,10,-10,10])
plt.show()

Edit I copied my own code wrong, now it is compiling if you have the right packages installed.


Solution

  • The built-in turtle module could be used to draw the path at a perceptible rate.

    import turtle
    
    turtle.speed('slowest')
    
    walk = randomWalkb(25)
    
    for x, y in zip(*walk):
        #multiply by 10, since 1 pixel differences are hard to see
        turtle.goto(x*10,y*10)
    
    turtle.exitonclick()
    

    Sample result:

    enter image description here