数据漫步

random_walk.py

#coding:gbk
from random import choice
class RandomWalk():
    def __init__(self, num_points = 5000):
        self.num_points = num_points
        
        #初始点为(0,0)
        self.x = [0]
        self.y = [0]
    
    def fill_walk(self):
        while len(self.x) < self.num_points:
            
            #确定x方向上前进的距离和方向
            x_direction = choice([1, -1])
            x_distance = choice([0, 1, 2, 3])
            x_step = x_direction * x_distance
            
            #确定y方向上的移动
            y_direction = choice([1, -1])
            y_distance = choice([0, 1, 2, 3])
            y_step = y_direction * y_distance
            
            #不移动的时候不进行操作,避免重复绘制点
            if x_step ==0 and y_step == 0:
                continue      
            
            #x, y 下一次所移动的位置
            next_x = self.x[-1] + x_step
            next_y = self.y[-1] + y_step
            
            #将下一步x,y的位置添加到列表
            self.x.append(next_x)
            self.y.append(next_y)

rw_visual.py

#coding:gbk
import matplotlib.pyplot as plt
from random_wark import RandomWalk

while True:
    #创建一个实例,并生成漫步点的全部坐标
    
    num = int(input("请输入参与漫步点的数量:"))
    rw = RandomWalk(num)
    rw.fill_walk()
    
    #绘制
    plt.figure(dpi=128, figsize=(10, 6))
    plt.scatter(rw.x, rw.y, c = rw.y, cmap = plt.cm.Blues, s = 5)
    
        #突出起始点坐标
    plt.scatter(0, 0, c = 'red', edgecolors = 'none', s = 100)
    plt.scatter(rw.x[-1], rw.y[-1], c = 'yellow', edgecolors = 'none', s = 100)
    
        #隐藏坐标轴
    plt.axes().get_xaxis().set_visible(False)
    plt.axes().get_yaxis().set_visible(False)
    plt.show()
    
    keep_running = input("Make another walk?(y/n): ")
    if keep_running == 'n':
        break

你可能感兴趣的:(数据可视化)