绘制随机漫步图

matplotlib可绘制随机漫步图,取随机X个数,在画布上绘制,并加入渐变颜色,效果还是挺好看的

代码如下:

random_walk.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from random import choice

class RandomWalk():
"""一个生成随机漫步数据的类"""

def __init__(self,num_point=5000):
"""初始化随机漫步的属性"""
self.num_point = num_point

#所有随机漫步的点都始于(0,0)
self.x_values = [0]
self.y_values = [0]

def get_step(self):
"""设置前进方向及距离"""
direction = choice([1, -1])
distance = choice([0, 1, 2, 3, 4])
step = distance * direction
return step

def fill_walk(self):
"""计算随机漫步的所有点"""
while len(self.x_values) < self.num_point:
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)


rw_visual.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from random_walk import RandomWalk

while True:
#创建一个随机漫步实例,并将所有包含的点绘制出
rw = RandomWalk(30000)
rw.fill_walk()

point_num = list(range(rw.num_point))
plt.scatter(rw.x_values, rw.y_values, c=point_num, cmap=plt.cm.Blues, s=5)
#突出起点和终点
plt.scatter(0, 0, c='green', s=100)
plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', s=100)

#隐藏坐标轴
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
#plt.subplot().set_xticks([])
#plt.subplot().set_yticks([])

plt.show()

keep_drawing = input("Make another walk?y/n")
if keep_drawing == 'n':
break

可成功绘制随机漫步图,然而有个警告报错:

1
MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance.  In a future version, a new instance will always be created and returned.  Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.warnings.warn(message, mplDeprecation, stacklevel=1)

原因是matplotlib版本问题,出在隐藏坐标轴plt.axes().get_yaxis()处,尝试修改为:

1
2
plt.subplot().set_xticks([])
plt.subplot().set_yticks([])

然而没啥用,还是在警告,暂时没解决。。好在不影响功能,不是强迫症也就无视这红字了。。

文章目录
  1. random_walk.py
  2. rw_visual.py
|