创建Randomwalk()类
我们将使用Python来生成随机漫步数据,再使用matplotlib以引入瞩目的方式将这些数据呈现出来
首先创建类Randomwalk()
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]
def fill_walk(self):
\'\'\'计算随机漫步的所有点\'\'\'
# 不断漫步,直到列表到达指定长度
while len(self.x_values)<self.num_points:
# 决定前进方向以及沿这个方向前进的距离
x_direction = choice([1,-1])
x_distance = choice([0,1,2,3,4])
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:
continue
#计算下一个点的x和y值
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)
__init__()和fill_walk(),其中后者计算随机漫步经过的所有点。
我们使用choice([1,-1])给direction选择一个值,结果要么是表示向右走1,要么表示向左走-1,接下来,choice([0,1,2,3,4])随机的选择一个0~4之间的整数,告诉Python沿着指定的方向走多远(x_distance)
绘制随机漫步图
import matplotlib.pyplot as plt
from matplotlib_test.random_walk import RandomWalk
#创建一个RandomWalk实例,并将其包含的点都绘制出来
rw = RandomWalk()
rw.fill_walk()
print(rw.x_values)
plt.scatter(rw.x_values,rw.y_values,s=15)
plt.show()
运行结果:

我们首先导入模块pyplot和Randomwalk类,然后我们创建一个实例,并将其存储到rw中,再调用fill_walk(),我们将随机漫步的x与y值传递给scatter(),并选择了合适的点尺寸,显示包含5000个点的随机漫步。
模拟多次随机漫步
import matplotlib.pyplot as plt
from matplotlib_test.random_walk import RandomWalk
#只要程序处理活动状态,就不断的随机模拟
while True:
#创建一个RandomWalk实例,并将其包含的点都绘制出来
rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values,rw.y_values,s=15)
plt.show()
keep_running = input("Make another walk?(y/n):")
if keep_running == \'n\':
break
这些代码模拟一次随机漫步,在matplotlib查看器中显示结果,再不关闭查看器的情况下暂停。如果你关闭了查看器,程序询问你是否再模拟一次随机漫步,如果你输入y,那么将继续,如果你输入n,那么将退出。
设置随机漫步图样式
1.给点着色

我们使用颜色映射来指出个点的先后顺序,并删除每个点的黑色轮廓,让他们的颜色更明显,为根据漫步中各点的先后顺序进行着色,我们传递参数c,并将其设置为一个列表,其中包含个点的先后顺序。
运行结果:

2.重新绘制起点与终点
为了凸显上图的起点跟终点,我们可以这么做

运行结果:

3.隐藏坐标轴
为了修改坐标轴,使用函数plt.axes()来将坐标轴的可见性设置为False

运行结果:

4.增加点数
下面我们增加点数,在创建RandomWalk实例时增大num_points的值

运行结果:

5.调整窗口的尺寸大小
图表适合屏幕大小时,更有效的将数据中的规律呈现出来

窗口明显变大

如果知道自己系统的分辨率,还可以使用形参dpi传递该分辨率
plt.figure(dpi=128,figsize=(10,6))