随机漫步生成是无规则的,是系统自行选择的结果。根据设定的规则自定生成,上下左右的方位,每次所经过的方向路径。
首先,创建一个RandomWalk()类和fill_walk()函数
random_walk.py
from random import choice class Randomwalk (): '''一个生成随机数漫步的类''' def __init__(self,num_point=5000): '''初始化随机漫步的属性''' self.num_point = num_point #所有随机漫步的开始都是坐标[0,0] self.x_lab = [0] self.y_lab = [0] def fill_walk(self): '''计算随机漫步的所有点''' while len(self.x_lab) < self.num_point: #决定前进方向以及前进的距离 x_direction = choice([1,-1]) x_distance = choice([0,1,2,3,4]) x_step = x_direction * x_distance y_direction = choice([1,-1]) y_distance = choice([0,1,2,3,4]) y_step = y_direction * y_distance #拒绝原地不动 if x_step == 0 and y_step == 0: continue #计算下一个点X和Y的值 next_x = self.x_lab[-1] + x_step next_y = self.y_lab[-1] + y_step self.x_lab.append(next_x) self.y_lab.append(next_y)
2、绘制随机漫步图
rw_visual.py
import matplotlib.pyplot as plt from random_walk import Randomwalk from random import choice rw = Randomwalk() rw.fill_walk() plt.scatter(rw.x_lab,rw.y_lab,s=15) plt.show()
3、生成效果图片
4、修改代码-->隐藏边框
rw_visual.py
import matplotlib.pyplot as plt from random_walk import Randomwalk from random import choice while True: rw = Randomwalk() rw.fill_walk() #设置绘画窗口大小 plt.figure(dpi=128,figsize=(10,6)) point_numbers = list(range(rw.num_point)) #突出起点(0,0)和终点 plt.scatter(0,0,c='green',edgecolors='none',s=100) plt.scatter(rw.x_lab[-1],rw.y_lab[-1],c='red',edgecolors='none',s=100) #隐藏坐标轴 plt.axes().get_xaxis().set_visible(False) plt.axes().get_yaxis().set_visible(False) plt.scatter(rw.x_lab,rw.y_lab,c=point_numbers,cmap=plt.cm.Blues,edgecolors='none',s=15) plt.show() keep_running = input("Make another walk?(y/n): ") keep_running = keep_running.lower() if keep_running == 'n': break
5、展示效果