Python3实现简单的随机漫步散点图

import matplotlib.pyplot as plt
from random import choice

class RandomStep():
    def __init__(self,num_steps=5000):
        self.steps = num_steps

        self.x_points = [0]
        self.y_points = [0]

    def fill_points(self):
        while (len(self.x_points) < self.steps):
            x_dir = choice([-1,1])                    #设置随机漫步的方向
            x_dit = choice([0,1,2,3,4])               #每次漫步的距离
            x_steps = self.x_points[-1] + x_dir*x_dit #得到最新点的x
            y_dir = choice([-1,1])
            y_dit = choice([0,1,2,3,4])
            y_steps = self.y_points[-1] + y_dir*y_dit

            if x_steps==0 and y_steps==0:             #如果新随机点位置没更新 继续寻找
                continue
            self.x_points.append(x_steps)             #更新
            self.y_points.append(y_steps)
        return self.x_points, self.y_points
    
while True:
    choose = input("Would you want to make a Random walking scatters? y/n:")
    if choose == 'y':
        num_points = list(range(0,RandomStep().steps))#设计一个数量大小列表
        x,y = RandomStep().fill_points()              #调用类,需要带括号
        plt.figure(figsize=(10,6),dpi=128)            #设置画布大小以及dpi
        plt.title("RandomWalking",fontsize=14)        
        plt.scatter(x[0],y[0],c='green',s=20)         #绿色起点
        plt.scatter(x[-1],y[-1],c='red',s=20)         #红色终点
        plt.scatter(x,y,c=num_points,s=4,edgecolors='none',cmap=plt.cm.Blues)#蓝色渐变,c的参数是列表
        plt.axes().xaxis.set_visible(False)           #隐藏坐标轴
        plt.axes().yaxis.set_visible(False)
        plt.savefig("/home/pycharm/Project_one/walking.png",bbox_inches='tight')
        plt.show()
    elif choose == 'n':
        break

你可能感兴趣的:(Python)