在書中第15章最後作者要求用pygal替換matplotlib實現隨機漫步效果
代碼如下:
random_walk.py
1 #!/usr/bin/env python3
2 #-*- coding:utf-8 -*-
3
4 # 隨機漫步1
5
6 from random import choice
7
8 class RandomWalk():
9 """一個生成隨機漫步數據的類"""
10
11 def __init__(self, num_points=5000):
12 """初始化隨機漫步的屬性"""
13 self.num_points=num_points
14
15 # 所有隨機漫步都始於(0, 0)
16 self.x_values = [0]
17 self.y_values = [0]
18
19 def get_step(self):
20 """決定前進方向以及沿這個方向前進的距離"""
21 direction = choice([1, -1])
22 distance = choice([0, 1, 2, 3, 4])
23 step = direction * distance
24 return step
25
26 def fill_walk(self):
27 """計算隨機漫步包含的所有點"""
28
29 # 不斷漫步, 知道列表達到指定的長度
30 while len(self.x_values) < self.num_points:
31 # 決定前進方向以及沿這個方向前進的距離
32 x_step = self.get_step()
33 y_step = self.get_step()
34
35 # 拒絕原地踏步
36 if x_step == 0 and y_step == 0:
37 continue
38
39 # 計算下一個點的x和y值
40 next_x = self.x_values[-1] + x_step
41 next_y = self.y_values[-1] + y_step
42
43 self.x_values.append(next_x)
44 self.y_values.append(next_y)
rw_visual.py
1 #!/usr/bin/env python3
2 #-*- coding:utf-8 -*-
3
4 # 隨機漫步2
5 # 繪製隨機漫步圖
6
7 import pygal
8
9 from random_walk import RandomWalk
10
11 # 創建一個RandomWalk實例, 並將其包含的點都繪製出來
12 rw = RandomWalk(5000)
13 rw.fill_walk()
14
15 # 繪製點並將圖像顯示出來
16 point_numbers = list(range(rw.num_points))
17 chart = pygal.XY(stroke=False)
18
19 # 將x,y合併成座標並存入列表xy
20 xy = list(map(lambda x,y: (x, y), rw.x_values, rw.y_values))
21
22 chart.add('step', xy)
23 chart.render_to_file('step.svg')
效果圖如下: