请使用random和matplotlib解答

假設有個人,一開始在x坐標軸上的x=0處.
每過一秒,它會隨機地往左或右走1步
記錄過了1秒, 2秒, 100000秒後,它距離x=0的矩離
把距離和時間的關系畫出來(二維平面圖,x軸為時間,y軸為距離
把程序運行5次,把5張圖按順序貼到word裏,並說明這是第幾次運行

img

# 随机漫步demo,优化绘制,使用随机颜色随机散点大小绘制
from random import choice

import numpy as np
from matplotlib import pyplot as plt

# 支持中文
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False


class RandomWalk():
    """一个生成随机漫步数据的类"""
    num_points = 0
    x_values = []
    y_values = []
    dis_values = []

    def __init__(self, num_points=500):
        self.num_points = num_points
        # 所有随机漫步都始于(0,0)
        self.x_values = [0]
        self.y_values = [0]
        self.dis_values = [0]

    def fill_walk(self):
        while len(self.x_values) < self.num_points:
            # 决定前进方向
            x_direction = choice([1, -1])
            x_distance = 1
            x_step = x_direction * x_distance
            # 计算下一个点的x和y
            next_x = self.x_values[-1] + x_step
            next_y = 0
            self.x_values.append(next_x)
            self.y_values.append(next_y)
            if (len(self.x_values) > 0):
                self.dis_values.append(next_x - 0)
            else:
                self.dis_values.append(x_step)


x = np.arange(10000)


x = np.arange(10000)

# for i in np.arange(5):
#     rw = RandomWalk(num_points=10000)
#     rw.fill_walk()
#     plt.scatter(x, rw.dis_values, s=5,marker='*')
#     plt.title("第"+str(i+1)+"次运行结果")
#     plt.show()
    
for i in np.arange(5):
    ax = plt.subplot(111)
    rw = RandomWalk(num_points=10000)
    rw.fill_walk()

    # c 指定随机颜色
    # s 指定散点的半径大小
    # cmap 指定使用jet调色板
    c = np.random.randint(0, 5, size=len(x))
    s = np.random.randint(3, 100, size=len(x))
    ax.scatter(x, rw.dis_values, c=c, s=s, cmap="jet", marker="o", linewidths=0)
    ax.set_title("第" + str(i + 1) + "次运行结果")
    plt.show()