Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 416
90intuition Avatar asked Dec 26 '22 01:12

90intuition


2 Answers

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

like image 105
Kevin Avatar answered Jan 09 '23 04:01

Kevin


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))
like image 44
Raphael Roth Avatar answered Jan 09 '23 04:01

Raphael Roth