python - 如何使用 Pygal 进行随机游走的可视化?
问题描述
我一直在 Python Crash Course(练习 15.10)中进行这个练习,我需要使用 Pygal 可视化随机游走。最终的图表应该看起来像一个直方图。在自己无法弄清楚之后,我四处寻找解决方案并将我能找到的内容拼凑到下面的代码中。但是,该代码不起作用并且出现诸如“RandomWalk 元素没有属性“fill_walk””之类的错误。我认为它确实具有此属性,因为我将 random_walk 导入 random_walk_visulization。有人可以帮我创建这个图表吗?谢谢!
random_walk.py
from random import choice
class RandomWalk():
"A class to regerate random walks"
def __init__(self, num_points = 5000):
self.num_points= num_points
#All walks start at (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
#Reject steps that go nowhere
if x_step == 0 and y_step == 0:
continue
#Calculate the next x and y values
next_x = self.x_values[-1] + x_step
next_y = self.y_values[-1] + y_step
#Append/add on the next_x and y values to self.x and y values
self.x_values.append(next_x)
self.y_values.append(next_y)
random_walk_visualization
import matplotlib.pyplot as plt
import pygal
from random_walk import RandomWalk
# Make a random walk, and plot the points.
rw = RandomWalk()
rw.fill_walk()
# Visualize the rw with pygal.
scat = pygal.XY(stroke=False)
scat.add('rw', list(zip(rw.x_values, rw.y_values)))
scat.render_to_file('rw_visual.svg')
# Set the size of the plotting window
plt.figure(figsize=(10, 6))
point_numbers = list(range(rw.num_points))
plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.copper,
edgecolor='none', s=2)
# emphasize the first and last points.
plt.scatter(0, 0, c='green', edgecolor='none', s=100)
plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none',
s=100)
# Remove the axes.
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
plt.show()
解决方案
推荐阅读
- mysql - 如何在不切割某一列的情况下对 sql 表进行分页
- android - getDownloadURL 没有输入我需要的链接
- php - Woocommerce 自定义电子邮件
- sql - Postgres:通过通用电子邮件地址将帐户聚合为一个身份
- pandas - 熊猫根据条件切片并选择
- azure - Application Insights 日志查询获取组中的最新行
- reactjs - 反应导出 withRouter 和 withStyles 错误
- mysql - 基于两个表选择记录,其中一个表中的一列使用 SQL 以另一表列中的记录开头
- python - 如何知道给定列中具有不同形状的单元格
- xamarin - Xamarin.UITest AppCenter 找不到 test-cloud.exe