Question

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.

Was it helpful?

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

OTHER TIPS

I would visualize the time-information using a color, i.e. try to plot

plt.plot(walk[0],walk[1],label= 'Random walk')
plt.scatter(walk[0],walk[1],s=50,c=range(26))

See the animation tutorial at http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/

In this case the animate function should perform one step of your walk and set the x-y data appropriately. If you don't care to save the animation or don't have the codec installed, just ignore the anim.save call.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top