本文地址https://blog.csdn.net/sidens/article/details/80710303,转载请说明
在《Python编程:从入门到实践》一书中,作者使用的是使用matplotlib包实现随机漫步
如下:
import matplotlib.pyplot as plt
from random import choice
class RandomWalk():
"""一个随机漫步类"""
def __init__(self,num_point=5000):
"""初始化随机漫步属性"""
self.num_point = num_point
#随机漫步的起始点是坐标原点
self.x_values = [0]
self.y_values = [0]
def get_step(self):
"""计算当前移动步长"""
#决定前进的方向和长度,1表示向右,-1表示向左
possible_distances = list(range(0,11))
possibel_directions = [1,-1]
distance = choice(possible_distances)
direction = choice(possibel_directions)
return distance * direction
def fill_walk(self):
"""计算随机漫步包含的所有点"""
while(len(self.x_values) < self.num_point):
#得到x轴和y轴上应该移动的步长
x_step = self.get_step()
y_step = self.get_step()
#当前坐标等于上一次的·坐标加上增量
x_current = self.x_values[-1] + x_step
y_current = self.y_values[-1] + y_step
self.x_values.append(x_current)
self.y_values.append(y_current)
if __name__ == '__main__':
rw = RandomWalk()
num_points = list(range(rw.num_point))
rw.fill_walk()
plt.scatter(rw.x_values,rw.y_values,s=1,c=num_points,cmap=plt.cm.Blues)
plt.title('RandomWalk')
#使起点和终点更明显
plt.scatter(0,0,s=20,c='green')
plt.scatter(rw.x_values[-1],rw.y_values[-1],s=20,c='red')
#隐藏坐标轴
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
plt.show()
生成的随机漫步图如下所示:
接下来,使用pygal包完成类似的操作
在pygal的官方网站https://www.pygal.org上找到这样的实例:
xy_chart = pygal.XY(stroke=False)
xy_chart.title = 'Correlation'
xy_chart.add('A', [(0, 0), (.1, .2), (.3, .1), (.5, 1), (.8, .6), (1, 1.08), (1.3, 1.1), (2, 3.23), (2.43, 2)])
xy_chart.add('B', [(.1, .15), (.12, .23), (.4, .3), (.6, .4), (.21, .21), (.5, .3), (.6, .8), (.7, .8)])
xy_chart.add('C', [(.05, .01), (.13, .02), (1.5, 1.7), (1.52, 1.6), (1.8, 1.63), (1.5, 1.82), (1.7, 1.23), (2.1, 2.23), (2.3, 1.98)])
xy_chart.render()
这个实例生成的图像如下所示:
基于此,我写了如下代码:
import pygal
from random import choice
class RandonWalk():
"""一个随机漫步类"""
def __init__(self,num_points=5000):
"""初始化随机漫步属性"""
self.num_points = num_points
#起点为坐标原点
self.x_values = [0]
self.y_values = [0]
def get_step(self):
"""得到下次要走的步长"""
possible_distances = list(range(11))
#1表示右,-1表示左
possible_directions = [1,-1]
distance = choice(possible_distances)
direction = choice(possible_directions)
return distance * direction
def fill_walk(self):
"""计算随机漫步包含的所有点"""
while len(self.x_values) < self.num_points:
x_step = self.get_step()
y_step = self.get_step()
#当前坐标等于上次坐标加当前步长
x_distance = self.x_values[-1] + x_step
y_distance = self.y_values[-1] + y_step
self.x_values.append(x_distance)
self.y_values.append(y_distance)
if __name__ == '__main__':
rw = RandonWalk()
rw.fill_walk()
xy_chart = pygal.XY(stroke=False)
xy_chart.title = 'RandomWalk'
xy_chart.add('A',[(rw.x_values[i],rw.y_values[i]) for i in range(0,rw.num_points)])
xy_chart.render_to_file('RandomWalk.svg')
其中,第43行代码使用列表解析
以下代码不能替换第43行代码,因为列表只支持key的迭代,key,value的迭代需要字典支持
xy_chart.add('A',[(x,y) for x,y in rw.x_values, rw.y_values])
初学者可能会使用如下方法使用字典,这样做忽视了字典中key值唯一不重复的特性,丢失了很多点
#创建坐标点字典
point = {}
for i in range(rw.num_points):
point[rw.x_values[i]] = rw.y_values[i]
#列表解析 key,value迭代
xy_chart.add('A',[(x,y) for x,y in point.items()])
以下代码同一key值对应多个value值,不存在丢失点的情况
from collections import OrderedDict
#创建坐标点字典
point = OrderedDict()
for i in range(rw.num_points):
point[i] = (rw.x_values[i],rw.y_values[i])
#列表解析 key,value迭代
xy_chart.add('A',[(x,y) for x,y in point.values()])
这里使用OrederedDict类仅表示我们不仅重视键值对的对应关系,还重视键值对的添加(生成)顺序,对随机漫步点图的生成无影响,如果要生成路径图,必须使用OrederedDict类。
运行结果如图所示:
经实际检验,以上使用pygal包的代码能够完成与使用matplotlib包类似的随机漫步效果。