[Generate data] random walk

Use python to generate random walk data, and then use matplotlib to present these data.

Random walk: Each walk is completely random, with no clear direction, and the outcome is determined by a sequence of random decisions. It can also be considered that a random walk is the path that the ants travel along each time in a random direction when they are dizzy.

random_walk.py

Create the RandomWalk() class

To simulate a random walk, create a class called RandomWalk that randomly chooses a direction to go.

  • Three attributes:
    a variable that stores the number of random walks;
    stores the x and y coordinates of each point that the random walk passes through (two lists)
  • Two methods:
    __init() Generate random walk data
    fill_walk() Calculate all points passed by random walk

Initialize the attributes of the random walk __init()

from random import choice
#每次做决定时都是用choice来决定使用那种选择

"""
一个生成随机漫步数据的类
"""
class RandomWalk():

    def __init__(self, num_points=5000):
        """初始化随机漫步的属性"""
        
        #默认点数为5000
        self.num_points = num_points

        #所有随机漫步都from(0,0)
        self.x_values = [0]
        self.y_values = [0]

Select direction fill_walk()

Generate the points included in the walk and determine the direction of each walk

    """计算随机漫步包含的所有点"""
    def fill_walk(self):
        #不断漫步,知道列表达到指定的长度
        while len(self.x_values) < self.num_points:
            #决定前进方向以及沿着个方向前进的距离
            x_direction = choice([1, -1])#左右
            x_distance = choice([0, 1, 2, 3, 4])#距离
            x_step = x_direction * x_distance

            y_direction = choice([1, -1])
            y_distance = choice([0, 1, 2, 3, 4])
            y_step = y_direction * y_distance

            #拒绝原地踏步
            if x_step == 0 and y_step == 0:
                continue

            #计算下一个点的x和y值
            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)

rw_visual.py

Draw a simple random walk graph

plot all the points of the random walk

Create a RandomWalk instance, call fill_walk, pass the x and y values ​​​​included in the random walk to scatter and display, the code is as follows:

import matplotlib.pyplot as plt
from random_walk import RandomWalk

#创建一个RandomWalk实例,并将其包含的点都绘制出来
rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values, rw.y_values, s=15)
plt.show()

The following are two random walks with 5000 points
insert image description here

insert image description here

Simulate multiple random walks

Each random walk is different, so put this code in a while loop to look at multiple walks:

#只要程序处于活动状态,就不断地模拟随机漫步
while True:
    #创建一个RandomWalk实例,并将其包含的点都绘制出来
    rw = RandomWalk()
    rw.fill_walk()
    plt.scatter(rw.x_values, rw.y_values, s=15)
    plt.show()

    keep_running = input("Make another walk?(y/n):")
    if keep_running == 'n':
        break

Styling the Random Walk Plot

color the dots

Use a color map to indicate the order of the points in the walk, and remove the black outline of each point, making them more visible in color.

To color according to the order of the points in the walk, pass the parameter c and set it as a list containing the order of the points. Since these points are drawn in order, the list specified for the parameter c only needs to be Contains numbers 1-5000:

 plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolor='none', s=15)

Set the parameter c to point_numbers, specify to use the color map Blues, and pass the actual parameter edgecolor='none' to delete the outline around each point, the final random walk map changes from light blue to dark blue, and the coloring effect is shown in the figure Show:
insert image description here

insert image description here

Redraw start and end points

In addition to coloring the points of each random walk to indicate their order, you can also redraw the start and end points after plotting the random walk.

Let the start and end points become larger and displayed in different colors, the code is as follows:

    #突出起点和终点
    plt.scatter(0, 0, c='green', edgecolors='none', s=100)
    plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=100)

To highlight the starting point, the point (0,0) is drawn in green, and s=100 makes it larger than the other points.
To highlight the end point, draw a point at the last point (x,y) of the walk, set its color to red, and s=100 to make it larger than the other points.

A random walk graph looks like this:
insert image description here
insert image description here

increase points

Increase the value of num_points when creating the RandomWalk instance, and resize each point when drawing, as follows:

#只要程序处于活动状态,就不断地模拟随机漫步
while True:
    #创建一个RandomWalk实例,并将其包含的点都绘制出来
    rw = RandomWalk(50000)
    rw.fill_walk()

    point_numbers = list(range(rw.num_points))
    plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolor='none', s=1)
    # plt.scatter(rw.x_values, rw.y_values, s=15)

    #突出起点和终点
    plt.scatter(0, 0, c='green', edgecolors='none', s=100)
    plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=100)

    plt.show()

    keep_running = input("Make another walk?(y/n):")
    if keep_running == 'n':
        break

A random walk with 50,000 points is shown in the figure:
insert image description here

insert image description here

Hide Axes

Set the visibility of each axis to False

    #隐藏坐标轴
    # plt.axes().get_xaxis().set_visible(False)
    # plt.axes().get_yaxis().set_visible(False)
    current_axes = plt.axes()
    current_axes.xaxis.set_visible(False)
    current_axes.yaxis.set_visible(False)

The result of hiding the coordinate axes is shown in the figure:
insert image description here

Set the size of the drawing window

    plt.figure(figsize=(10,6))

insert image description here

The resolution can be passed to figure() using the dpi parameter to efficiently use the available screen space:

    plt.figure(dpi=128, figsize=(10, 6))

Guess you like

Origin blog.csdn.net/m0_50609545/article/details/131029971