Python 随机漫步练习

使用Python matplotlib 实现简单的随机漫步并生成图像

准备阶段

若没有matplotlib库,安装方法如下

pip install matplotlib

代码实现

首先,创建一个用来模拟随机漫步的类

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_step = self.get_step()
            y_step = self.get_step()

            #拒绝原地踏步
            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)
    
    def get_step(self):
        #决定前进方向以及沿着个方向前进的距离
        direction = choice([1, -1])
        distance = choice([0, 1, 2, 3, 4, 5])
        step = direction * distance

        return step

使用matplotlib绘制随机漫步图

import matplotlib.pyplot as plt
from random_walk import RandomWalk
#创建RandomWalk实例 绘制包含的点
rw = RandomWalk(10000)
rw.fill_walk()

plt.title("RandomWalk")
point_numbers = list(range(rw.num_points))
plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolors='none', s=2)

#突出起点终点
plt.scatter(0, 0, c='green', edgecolors='none', s=30)
plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=30)
#隐藏坐标轴
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)

plt.show()

最终结果如下
在这里插入图片描述
如果想要保存图片,可以调用plt.savefig()替换plt.show()

plt.savefig('RandomWalk.png', bbox_inches='tight')

猜你喜欢

转载自blog.csdn.net/qq_44132542/article/details/86727550