首先我们创造一个名为RandomWalk的类,它需要三个属性
一是储存随机漫步次数的变量,其他俩个是储存漫经过的x和y
我们使用的是choice()来选择
这里我们默认 的点数为5000,足够生成一个奇妙的图形
每次漫步从(0,0)出发
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_direction = choice([1, -1])
x_distance = choice([0, 1, 2, 3, 4])
x_step = x_distance * x_direction
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
next_y = self.y_values[-1] + y_step
self.x_values.append(next_x)
self.y_values.append(next_y)
在fill_walk()我们做了一个循环,直到漫步包含所需数量的点。
使用choice()进行选择上下左右的随机挑选
最后设置了不能原地踏步,拒绝这样的情况,接着执行下一次循环。、
绘制随机漫步图
我们要导入pyplot和RandomWalk类,然后创建RandomWalk实例储存到rw中,在调用fill_walk()
import matplotlib.pyplot as plt
from random_walk import RandomWalk
while True:
rw = RandomWalk(50000)
rw.fill_walk()
# 设置绘制窗口的尺寸
plt.figure(dpi=100, figsize=(10, 6))
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=1)
# 突出起点,终点
plt.scatter(0, 0, c='green', edgecolors='none', s=10)
plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=10)
# 隐藏坐标轴
plt.axis('off')
plt.show()
keep_running = input("Make another walk? (y/n):")
if keep_running == 'n':
break
plt.axis()可以修改坐标轴,隐藏起来
函数figure()用于指定图标的宽度,高度,分辨率和背景色,指定一个元组指出尺寸为英寸
形参dpi则是传递分辨率
plt.figure(dpi=100, figsize=(10, 6))