Python从入门到实践随机漫步绘图

大家好,Python从入门到实践中绘制随机漫步图中遇到了问题,代码部分仔细排查过但画出的图一直是一条竖线,请了解的朋友帮忙指点以下,谢谢!

img

img

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]

    def fill_walk(self):
        # 不断漫步,直到列表达到指定的长度
        while len(self.x_values) < self.num_points:
            # 决定x的方向和距离
            # 决定方向
            x_direction = choice([1, -1])
            # 决定距离
            x_distance = choice([0, 1, 2, 3, 4])
            x_step = x_distance * x_direction

            # 决定y的方向和距离
            # 决定方向
            y_direction = choice([1, -1])
            # 决定距离
            y_distance = choice([0, 1, 2, 3, 4])
            y_step = y_distance * y_direction

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

            # 计算下一个点的坐标(x,y)
            next_x = self.x_values[-1] + x_step  # x坐标序列的最后一位 + x上的距离
            next_y = self.y_values[-1] + y_step

            # 在(x,y)坐标序列后加上下一个点的坐标
            self.x_values.append(next_x)
            self.y_values.append(next_y)





random_walk_sample.py


import matplotlib.pyplot as plt

from random_walk import RandomWalk

# 默认使用楷体
plt.rcParams['font.sans-serif'] = ['KaiTi']

while True:
    # 创建一个RandomWalk实例
    A = RandomWalk()
    A.fill_walk()

    # 画图
    fig, ax = plt.subplots()
    ax.scatter(A.x_values, A.y_values, s = 2)

    # 设置标题
    ax.set_title("随机漫步图", fontsize = 14)

    plt.show()

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



img