matplotlib之随机漫步

时间:2023-03-10 04:30:17
matplotlib之随机漫步
 # 随机漫步类
from random import choice
from matplotlib import pyplot as plt
from pylab import mpl
from matplotlib import rcParams class RandomWalk():
'''生成随机漫步的类''' def __init__(self, total_num=15000):
self.total_num = total_num
'''初始坐标(0,0)'''
self.x_values = [0]
self.y_values = [0] def get_step(self):
'''随机生成移动的方向和距离'''
diretion = choice([1, -1])
distance = choice([0, 1, 2, 3, 4, 5])
return diretion * distance def fill_walk(self):
'''计算随机漫步中所有的点'''
while len(self.x_values) < self.total_num:
'''计算前进方向和距离'''
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) # 设置默认字体,解决中文显示乱码问题
mpl.rcParams['font.sans-serif'] = ['SimHei']
# 解决负号'-'显示为方块的问题
rcParams['axes.unicode_minus'] = False # 随机漫步实例
rw = RandomWalk()
rw.fill_walk()
point_nunbers = list(range(rw.total_num)) # 调整绘图窗口尺寸,单位为英寸
plt.figure(figsize=(8, 6)) # 给点着色显示
plt.scatter(rw.x_values, rw.y_values, c=point_nunbers, cmap=plt.cm.Blues, s=1)
plt.title("随机漫步图", fontsize=18) # 突出起点和终点
plt.scatter(0, 0, c='green', s=30)
plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', s=20) # 隐藏坐标轴
# plt.axes().get_xaxis().set_visible(False)
# plt.axes().get_yaxis().set_visible(False) plt.show()

运行截图:

matplotlib之随机漫步