尘风
红尘往事,一切随风

 
randomwalk.py代码
 
from random import choice
 
class RandomWalk():
    def __init__(self,points=5000):
        self.points=points
        self.x=[0]
        self.y=[0]
    def random_walk(self):
        while len(self.x)<self.points: #当x的长度小于5000,也就是没有生成5000点之前都继续循环生成点
            x_direction=choice([1,-1]) #通过choice选择-1和1控制方向
            x_distance=choice([0,1,2,3,4]) #通过choice选择列表里面的值控制x移动距离
            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:#如果x,y移动都为0,我们就跳出本次操作,不加这个没有移动的点,然后继续循环生成存在移动的点再添加到x列表里面
                continue
            next_x=self.x[-1]+x_step #通过计算得到新点的x值
            next_y=self.y[-1]+y_step
            self.x.append(next_x)#通过append把新的x值添加到列表x中
            self.y.append(next_y)
 
绘图的代码
 
import matplotlib.pyplot as plt
from randomwalk import RandomWalk  #导入类
 
m=[2,4]
n=[3,2]
 
while True:
    random=RandomWalk(5000)#创建实例
    random.random_walk() #实例调用类方法
    plt.figure(dpi=80,figsize=(8,6)) #调整图像查看器的尺寸,dpi是像素大小,默认80
    plt.scatter(random.x,random.y,c=random.x,s=1,edgecolor='none',cmap=plt.cm.Blues) # 以x的集合生成循序绘制颜色渐变散点
    plt.scatter(random.x,random.y,c=random.y,s=1,edgecolor='none',cmap=plt.cm.Blues) # 以y的集合生成顺序绘制颜色渐变散点
    plt.scatter(0,0,c='red',s=40,edgecolor='none') # 重绘起点,通过设置和其它点的不同属性突出起点位置
    plt.scatter(random.x[-1],random.y[-1],c='yellow',s=40,edgecolor='none') #重绘终点,通过设置和其它点的不同属性突出终点位置
    plt.title('title',fontsize=10)
    plt.xlabel('variable',fontsize=10)
    plt.ylabel('value',fontsize=10)
    plt.tick_params(axis='both',labelsize=10)
    #plt.axis([0,5,0,5])
    #plt.savefig('imag.png',bbox_inches='tight')
    plt.axes().get_xaxis().set_visible(False) #隐藏x坐标轴
    plt.axes().get_yaxis().set_visible(False) #隐藏y坐标轴
    plt.show()
    check=input("你是否要继续查看随机漫步(y/n)") #通过输入函数在关闭图像查看器的时候提示是否重新生成随机漫步
    if check=='n':
        break
 
posted on 2020-09-07 23:25  一个行者  阅读(173)  评论(0编辑  收藏  举报