Python application examples (2) data visualization (2)

1. Random walk

Use Python to generate random walk data, and then use Matplotlib to present these data in a compelling way. A random walk is a path obtained by walking such that each walk is completely random, with no clear direction, and the outcome is determined by a series of random decisions. You can think of a random walk as the path that the ants follow in a random direction each time while they are bewildered.

Random walks have practical uses in nature, physics, biology, chemistry, and economics. For example, pollen floating on water droplets moves on the surface of the water as it is constantly squeezed by water molecules. Molecular motion in water droplets is random, so the path of pollen on the water surface is like a random walk. The code we write later will simulate many situations in the real world.

1.1 Create the RandomWalk class

To simulate a random walk, you'll create a class called RandomWalk that randomly chooses a direction to go. This class requires three properties: one is a variable that stores the number of random walks, and the other two are lists that store the x-coordinates and y-coordinates of each point passed by the random walk, respectively.

The RandomWalk class contains only two methods: the method __init___() and fill_walk(), which calculates all the points passed by the random walk. Let's take a look at __init__() first, as follows:

random_walk.py

from random import choice

  class RandomWalk:
      """一个生成随机漫步数据的类。"""
def __init__(self, num_points=5000):
          """初始化随机漫步的属性。"""
          self.num_points = num_points

          #所有随机漫步都始于(0, 0)。
❸         self.x_values = [0]
          self.y_values = [0]

To make a random decision, store all possible choices in a list and use choice() from the module random at each decision to decide which choice to use (see ❶). Next, set the default number of points included in the random walk to 5000. This number is large enough to generate interesting patterns, yet small enough to ensure fast simulation of random walks (see ❷). Then, create two lists at ❸ for storing the [illustration] value and the [illustration] value, and let each walk start from the point (0, 0).

1.2 Choose direction

We will use the method fill_walk() to generate the points included in the walk and determine the direction of each walk, as shown below. Please add this method to random_walk.py: random_walk.py

      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值。
❻             x = self.x_values[-1] + x_step
              y = self.y_values[-1] + y_step

              self.x_values.append(x)
              self.y_values.append(y)

A loop is established at ❶ that runs until the walk contains the required number of points. The main part of the method fill_walk() tells Python how to simulate four walking decisions: go right or go left? How far in the indicated direction? Go up or go down? How far in the chosen direction?

Using choice([1, -1]) to choose a value for x_direction results in either 1 for going right or -1 for going left (see ❷). Next, choice([0, 1, 2, 3, 4]) randomly selects an integer from 0 to 4 and tells Python how far to go in the specified direction (x_distance). By including 0, not only can you move along two axes at the same time, but you can also move along only one axis.

At ❸ and ❹, multiply the moving direction by the moving distance to determine the moving distance along the [inset] axis and the [inset] axis. If x_step is positive, it will move to the right, if it is negative, it will move to the left, if it is zero, it will move vertically; if y_step is positive, it will move up, if it is negative, it will move down, and if it is zero, it will move horizontally. If both x_step and y_step are zero, it means standing still. We reject this case and proceed to the next loop (see ❺).

To get the [inset] value for the next point in the walk, add x_step to the last value in x_values ​​(see ❻), and do the same for the [inset] value. Once you have the [inset] and [inset] values ​​for the next point, append them to the end of the lists x_values ​​and y_values, respectively.

1.3 Draw a random walk graph

The following code plots all the points of a random walk: rw_visual.py

  import matplotlib.pyplot as plt

  from random_walk import RandomWalk

  # 创建一个RandomWalk实例。
❶ rw = RandomWalk()
  rw.fill_walk()
  # 将所有的点都绘制出来。
  plt.style.use('classic')
  fig, ax = plt.subplots()
❷ ax.scatter(rw.x_values, rw.y_values, s=15)
  plt.show()

First import the module pyplot and the RandomWalk class, then create a RandomWalk instance and store it in rw (see ❶), and call fill_walk(). At ❷, the [inset] value and the [inset] value contained in the random walk are passed to scatter(), and an appropriate point size is chosen. Figure 15-9 shows a random walk graph with 5000 points. (The diagrams in this section do not include the Matplotlib viewer interface, but you will see it when you run rw_visual.py.)

insert image description here

1.4 Simulating multiple random walks

Every random walk is different, so it's fun to explore the various patterns that might be generated. One way to simulate multiple random walks using the previous code without running the program multiple times is to put the code in a while loop, like so: rw_visual.py

import matplotlib.pyplot as plt

from random_walk import RandomWalk

# 只要程序处于活动状态,就不断地模拟随机漫步。
while True:
    # 创建一个RandomWalk实例。
    rw = RandomWalk()
    rw.fill_walk()

    # 将所有的点都绘制出来。
    plt.style.use('classic')
    fig, ax = plt.subplots()
    ax.scatter(rw.x_values, rw.y_values, s=15)
    plt.show()

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

These codes simulate a random walk, display the results in the Matplotlib viewer, and pause without closing the viewer. If you close the viewer, the program will ask if you want to simulate another random walk. If you enter y, you can simulate random walks that take place near the start point, random walks that deviate mostly from the start point in a certain direction, random walks with non-uniform distribution of walk points, and so on. To end the program, enter n.

1.5 Styling the random walk graph

This section will customize the diagram to highlight the important features of each walk and to make distracting elements less prominent. To do this, we identified elements to be highlighted, such as the start, end and path of the walk. Next identify elements that you want to make less prominent, such as tick marks and labels. The end result is a simple visual representation that clearly indicates the path traveled by each walk.

color the dots

We'll use a color map to indicate the order of the points in the walk, and remove the black outline of each point to make it more prominently colored. 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. These points are drawn sequentially, so the list specified to the parameter c only needs to contain the numbers 0 to 4999, as follows: rw_visual.py

  --snip--
  while True:
      # 创建一个RandomWalk实例。
      rw = RandomWalk()
      rw.fill_walk()

      # 将所有的点都绘制出来。
      plt.style.use('classic')
      fig, ax = plt.subplots()
❶     point_numbers = range(rw.num_points)
      ax.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues,
          edgecolors='none', s=15)
      plt.show()

      keep_running = input("Make another walk? (y/n): ")
      --snip--

At ❶, range() is used to generate a list of numbers containing the same number of points as the walk contains. Next, store this list in point_numbers so you can use it later to set the color of each walk point. Set the parameter c to point_numbers, specify to use the colormap Blues, and pass the argument edgecolors='none' to remove the outline around each point. The final random walk plot fades from light blue to dark blue as shown.

insert image description here

Guess you like

Origin blog.csdn.net/qq_41600018/article/details/131749045