随机漫步
创建类
附上代码
from random import choice
class RandomWalk():
def __init__(self,num_points=5000):
"""初始化属性"""
self.num_points = num_points
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_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
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)
思路:创建类,在__init__函数中确定要漫步的次数,并且初始化x,y的值用列表表示。建立函数,在漫步次数不足时,进行如下操作:分别选择x,y的方向和漫步距离,且拒绝原地踏步,然后把位移后的位置至列表最后,至此,一个漫步类就形成了。
执行
在主文件中引入matplotlib.pyplot和前面定义的类,设置主循环,在用户需要时终止。绘制过程类比散点图,将前面定义的类中所得的x,y传入scatter()函数中,当然,在此之前不要忘记运行一次类中的漫步函数,从而为x,y列表添加够5000(默认)组坐标。
附代码:
import matplotlib.pyplot as plt
from matplotlib_work import RandomWalk
while True:
rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values,rw.y_values,s=15)
plt.show()
keep_running = input("Make another walk?(y/n):")
if keep_running == "n":
break
设置样式
1.着色:类似前面散点图的方法,找到点的个数,赋给c,并使用cmap确定颜色映射,在目前例子中,点的个数可以从类中获得,映射以蓝色为例,并将起点和终点进行标识。
point_number = list(range(rw.num_points))
plt.scatter(rw.x_values,rw.y_values,c=point_number,cmap=plt.cm.Blues,
edgecolor="none",s=15)
plt.scatter(0,0,c='red',edgecolor = 'none',s=100)
plt.scatter(rw.x_values[-1],rw.y_values[-1],c='red',edgecolor='none'
,s=100)
- 隐藏坐标轴:
函数 | 作用 |
---|---|
.axes().get_xaxis().set_visible(False) | 隐藏x轴 |
.axes().get_yaxis().set_visible(False) | 隐藏y轴 |
- 调整窗口尺寸:
.figure(dpi= ,figsize=(宽,高))