随机漫步
先建一个自己的类
from random import choice #使用模块random中choice()决定使用哪种选择
class RandomWalk: #生成随机漫步数据的类
def __init__(self,num_points=10000):#初始化随机漫步属性
self.num_points=num_points
self.x_values = [0]
self.y_values = [0]#建立储存x,y的值得列表,并让他们从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 #为0 则水平移动
if x_step == 0 and y_step == 0:
continue #等于0 则继续
x=self.x_values[-1]+x_step#在原来基础相加
y=self.y_values[-1]+y_step
self.x_values.append(x)
self.y_values.append(y)#新增的值添加到原来值的末尾
引用自己的类
from random_walk import RandomWalk#导入模块pyplot和RandomWalk类
import matplotlib.pyplot as plot
#创建一个RandomWalk实例
rw=RandomWalk()#创建实例并保存在rw 中
rw.fill_walk()#调用fill_walk()
plt.style.use('classic')
fig,ax=plt.subplots()
ax.scatter(rw.x_values,rw.y_values,s=15)#s这个参数是绘制图形时点的大小
plt.show()
总结:注意引用自己编写的类时要保证在同一文件夹下
2.注意书写规范
对图进行下一步修饰
import matplotlib.pyplot as plt
from random_walk import RandomWalk#导入模块pyplot和RandomWalk类
while True:
#创建一个RandomWalk实例
rw = RandomWalk(50_000)一次包含50000个点
rw.fill_walk()
#将所有的点绘制出来
plt.style.use('classic')
fig,ax = plt.subplots(figsize=(15,9))
point_numbers = range(rw.num_points)#生成一个数字列表,包含的数和漫步包含的点数量相同
ax.scatter(rw.x_values,rw.y_values,c=point_numbers,cmap=plt.cm.Blues,edgecolors='none',s=1)#s取一个更小的值
#s这个参数是绘制图形时点的大小,cmap告诉pyplot使用什么颜色映射,小的用浅色,大的用深色
ax.scatter(0,0,c='green',edgecolors='none',s=150)
ax.scatter(rw.x_values[-1],rw.y_values[-1],c='red',edgecolors='none',s=100)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
keep_running = input("Make another walk?(y/n):")
if keep_running == 'n':
break