对python应用的一个巩固,以及熟悉matplotlib的用法
效果如下:
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 28 22:39:55 2018
@author: pprp
"""
from random import choice
import matplotlib.pyplot as plt
class RandomWalk():
"""a class using to generate random data"""
def __init__(self,num_points=5000):
"""init the class"""
self.num_points=num_points
# start at (0,0)
self.x_val=[0]
self.y_val=[0]
def fill_walk(self):
"""calculate the points"""
while len(self.x_val) < self.num_points:
x_direction=choice([1,-1])
x_distance=choice([0,1,2,3,4,5])
x_step = x_direction * x_distance
y_direction=choice([1,-1])
y_distance=choice([1,2,5,4,0])
y_step = y_direction * y_distance
if x_step == 0 and y_step == 0:
continue
next_x = self.x_val[-1]+x_step
next_y = self.y_val[-1]+y_step
self.x_val.append(next_x)
self.y_val.append(next_y)
rw = RandomWalk(50000)
rw.fill_walk()
plt.tick_params(axis='both',labelsize=14)
point_nums=list(range(rw.num_points))
plt.scatter(rw.x_val,rw.y_val,s=1,c=point_nums,cmap=plt.cm.Blues,edgecolors='none')
# plot the start point and end point
plt.scatter(0,0,c='green',edgecolors='none',s=100)
plt.scatter(rw.x_val[-1],rw.y_val[-1],c='red',edgecolors='none',s=100)
# set figure width and height
plt.figure(dpi=1280,figsize=(10,6))
plt.show()