Python中的 matplotlib(二)随机漫步

创建一个随机漫步的类:

 1 from random import choice
 2 
 3 
 4 class RandomWalk():
 5     '''一个生成随机漫步数据的类'''
 6 
 7     def __init__(self, num_points=5000):
 8         '''初始化随机漫步的属性'''
 9         self.num_points = num_points
10         '''所有的随机漫步都始于(0,0)'''
11         self.x_values = [0]
12         self.y_values = [0]
13 
14     def fill_walk(self):
15         '''计算随机漫步的所有点'''
16         #不断漫步直到达到指定的长度
17         while len(self.x_values) < self.num_points:
18             #决定前进的方向以及沿着个方向的前进距离
19             x_direction = choice([1, -1])
20             x_distance = choice([0, 1, 2, 3, 4])
21             x_step = x_direction * x_distance
22 
23             y_direction = choice([1, -1])
24             y_distance = choice([0, 1, 2, 3, 4])
25             y_step = y_direction * y_distance
26             #拒绝原地踏步,跳出当前循环,开启下一次循环,重新选择漫步方向与距离
27             if x_step == 0 and y_step == 0:
28                 continue
29             #计算下一个点的x和y值
30             next_x = self.x_values[-1] + x_step
31             next_y = self.y_values[-1] + y_step
32 
33             self.x_values.append(next_x)
34             self.y_values.append(next_y)

绘制随机漫步图:

 1 import matplotlib.pyplot as plt
 2 from random_walk import RandomWalk
 3 
 4 '''模拟多次随机漫步'''
 5 while True:
 6 
 7     rw = RandomWalk()#可以使rw = RandomWalk(50000)以增加点数
 8     rw.fill_walk()
 9     #设置绘图窗口的尺寸(分辨率dpi/背景色等)
10     plt.figure(figsize=(10, 6))
11 
12     #根据漫步中各点的先后顺序给点着色
13     points_number = list(range(rw.num_points))
14     plt.scatter(rw.x_values, rw.y_values, c= points_number,
15                 cmap=plt.cm.Blues, edgecolors='none', s=15)
16     #突出起点和终点(重绘)
17     plt.scatter(0, 0, c='green', edgecolors='none', s=100)#起点绿色变大
18     plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red',
19                 edgecolors='none', s=100)#终点红色变大
20     #隐藏坐标轴
21     plt.axes().get_xaxis().set_visible(False)
22     plt.axes().get_yaxis().set_visible(False)
23 
24     plt.show()
25 
26     keep_running = input("Make another walk?(y/n):")
27     if keep_running == "n":
28         break

Figure:

 

posted @ 2019-04-16 20:07  椰汁软糖  阅读(308)  评论(0编辑  收藏  举报