本文将通过调用模块matplotlib.pyplot,实现随机漫步案例。
来学习如何绘制坐标点。python可视化是我们进行数据分析的良好工具。
文章将通过一个初始点从0.0开始,随机的移动,漫步,生成的结果显示再图上进行展示。
需要创建一个进行随机漫步的类,方向和移动举例都可以通过正负进行表示。
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 11 10:33:08 2020
@author: xuhaobo
"""
from random import choice
class RandomWalk():
#生成随机漫步的类
def __init__(self,num_points = 5000):
#初始化漫步的属性
self.num_points = num_points
#漫步起始于(0,0)
self.x_values = [0]
self.y_values = [0]
self.x_value = []
self.y_value = []
#重构后将移动距离函数分离
def get_step(self):
direction = choice([-1,1])
distance = choice([0,1,2,3,4])
step = direction*distance
return step
def fill_walk(self):
#不断漫步,直到到达指定长度
while (len(self.x_values)) < self.num_points:
#前进方向和距离
x_step = self.get_step()#调用距离计算函数
y_step = self.get_step()
#不可原地踏步
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)
# #方便可视化而创建
# self.x_value.append(x_step)
# self.y_value.append(y_step)
随后对移动的点进行显示,
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 11 10:51:57 2020
@author: xuhaobo
"""
import matplotlib.pyplot as plt
from random