Sharing some programming knowledge.

0%

Visualizing Random Walk In Python Using Matplotlib

Random Walk

A random walk is the process by which randomly-moving objects wander away from where they started. There are many kinds of Random Walk, but we only consider Lattice Random Walk Problem in this article, which simply assumes the object is walking on a lattice.

Matplotlib

Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. (from Matplotlib Documentation)

Simply put, it is one of python’s mathematical drawing libraries that can output figures based on input datas. Its function is similar to MATLAB. To install it, use pip install matplotlib.

Basic Usages of Matplotlib

Below are some basic usages of matplotlib that we will encounter in our Random Walk Program.

  • Basic Methods:
    • Import module pyplot: import matplotlib.pyplot as plt
    • Use plt.plot(x_values, y_values) to generate line graphs based on the given parameter, x_values and y_values are 2 lists.
    • Use plt.scatter(x_values, y_values) to generate scatter diagrams
    • Use plt.show() to display figures.
    • Use plt.savefig('path') to save figures.
  • Customize the figure:
    • Add title: plt.title("title", fontsize=20)
    • Add label to axes: plt.xlabel("x", fontsize=14) and plt.ylabel("y", fontsize=14)
    • Hide axes: plt.axes().get_xaxis().set_visible(False) and plt.axes().get_yaxis().set_visible(False)
    • Change the width of the line: plt.plot(list1, list2, linewidth=5)
    • Change the size of tick label: plt.tick_params(axis='both', labelsize=14)
    • Change the size of the dot: plt.scatter(x_values, y_values, s=200)
    • Add color to dots: plt.scatter(x_values, y_values, s=200, c='red')
    • Use color map:
      1
      2
      3
      4
      x_values = list(range(1,101))
      y_values = [x**2 for x in x_values]
      plt.scatter(x_values,y_values,c=y_values,cmap=plt.cm.Blues,s=40)
      # cmap tells pyplot which color to use; c tells pyplot how to render the color in different intensities, in this example, it sets dots with biger y-axis coordinate value as deep blue.

2D Random Walk Implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from random import choice
import matplotlib.pyplot as plt

class RandomWalk:
"""a class that emulate lattice random walk"""

def __init__(self, num_points=5000):
self.num_points = num_points # set the steps
self.x_values = [0] # x coordinate value, start from x =0
self.y_values = [0] # y coordinate value, start from y = 0

def get_step(self):
"""get each step's direction and distance"""
direction = choice([-1, 1])
distance = choice([0, 1, 2, 3, 4])
return direction * distance

def fill_walk(self):
"""fill x_values and y_values"""
while len(self.x_values) < self.num_points:

x_step = self.get_step()
y_step = self.get_step()

if x_step == 0 and y_step == 0: # refuse marching on the spot
continue

next_x = self.x_values[-1] + x_step
next_y = self.y_values[-1] + y_step

self.x_values.append(next_x)
self.y_values.append(next_y)

def show_walk(self):
point_numbers = list(range(self.num_points))
plt.scatter(self.x_values, self.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolors='none', s=1)
plt.scatter(0, 0, c='green', edgecolors='none', s=50) # highlight the start point
plt.scatter(self.x_values[-1], self.y_values[-1], c='black', edgecolors='none', s=50) # highlight the end point
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
plt.show()


if __name__ == '__main__':
while True:
rw = RandomWalk(50000)
rw.fill_walk()
rw.show_walk()
get_str = input("Make another walk? (y/n) ")
if get_str == "n":
break

Run the program, and we will get something beautiful like this:

It will vary every time. It’s quite interesting to see how it varies and what pattern it will produce.

Note that, roughly, the average distance between the start point and the end point is R*sqrt(N) where R is the average step-length and sqrt(N) is the square root of the number of steps.

What’s more, about lattice random walk problems, it’s interesting to think about that “What’s the probability that it’ll end up going through the starting point again?” Mathematicians have calculated the answers:

Dimension probability
1 100
2 100
3 34.0537
4 19.3206
5 13.5178
6 10.4715
7 8.58449
8 7.29126
( the data is from Pólya’s Random Walk Constants )

Though it’s glad to see that a drunken man would eventually find his way home, in most cases he will probably have to walk far more than 1 million steps to get home.


( After 1 million steps, he is still far from his home. )


( woooh, it only takes him 3826 steps! )

A try for 3D Random Walk Implementation

Of course, we could also try it on 3D lattice.
Just simply import Axes3D

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from random import choice
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

class RandomWalk:
def __init__(self, num_points=5000):
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
self.z_values = [0]

def get_step(self):
direction = choice([-1, 1])
distance = choice([0, 2, 4, 6, 8])
return direction * distance

def fill_walk(self):
while len(self.x_values) < self.num_points:

x_step = self.get_step()
y_step = self.get_step()
z_step = self.get_step()

if x_step == 0 and y_step == 0 and z_step == 0:
continue

next_x = self.x_values[-1] + x_step
next_y = self.y_values[-1] + y_step
next_z = self.z_values[-1] + z_step

self.x_values.append(next_x)
self.y_values.append(next_y)
self.z_values.append(next_z)

def show_walk(self):
point_numbers = list(range(self.num_points))
ax = plt.figure().add_subplot(111, projection='3d')
ax.scatter(self.x_values, self.y_values, self.z_values, c=point_numbers, cmap=plt.cm.brg, s=3)
ax.scatter(0, 0, 0, c='green', marker='^', s=200)
ax.scatter(self.x_values[-1], self.y_values[-1], self.z_values[-1], marker='o', c='black', s=200)
plt.title("3D Random Walk", fontsize=20)
plt.show()

if __name__ == '__main__':
while True:
rw = RandomWalk(1000)
rw.fill_walk()
rw.show_walk()

But I didnl’t get anything exciting:


( It starts from yellow to blue. )