Python 速成课程 15.10,使用 pygal 可视化随机游走

Python Crash Course 15.10, visualizing Random Walk using pygal

我正在阅读“Python 速成课程”这本书,我正在尝试用 pygal 想象随机游走。(练习 15.10)。

这是我的代码:

from random import choice

class RandomWalk():
    """A class to generate random walks."""

    def __init__(self, num_points=500):
        """Initialize attributes of a walk."""
        self.num_points = num_points

        # All walks start at (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 = direction * distance
        return step
        
        
    def fill_walk(self):
        """Calculate all the points in the walk."""

        # Keep taking steps until the walk reaches the desired length.
        while len(self.x_values) < self.num_points:
            # Decide which direction to go and how far to go in that direction.

            x_step = self.get_step()
            y_step = self.get_step()

            # Reject moves 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

            self.x_values.append(next_x)
            self.y_values.append(next_y)
            
#Visualizing with Pygal
import pygal

while True:
    rw = RandomWalk()
    rw.fill_walk()
    xy_chart=pygal.XY()
    xy_chart.title = 'Random Walk'
    rwValues=list(zip(rw.x_values,rw.y_values))
    xy_chart.add('rw',rwValues)
xy_chart.render_to_file('rw_visual.svg')

随机游走代码的逻辑很好,但我似乎无法理解如何使用 pygal 将其可视化。每当我 运行 代码(在 Jupyter notebook 上)时,notebook 都不会处理它。我尝试用 matplotlib 将其可视化,一切都很好。如果有人可以解释我做错了什么,那就太好了。 matplotib 代码的可视化是:

import matplotlib.pyplot as plt

# Keep making new walks, as long as the program is active.
while True:
    rw = RandomWalk()
    rw.fill_walk()
    plt.figure(figsize=(10, 10))
    point_numbers = list(range(rw.num_points))
    plt.plot(rw.x_values, rw.y_values,linewidth=1)
    plt.scatter(0, 0, c='green', edgecolors='none', s=100)
    plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none',
        s=100)
    plt.axes().get_xaxis().set_visible(False)
    plt.axes().get_yaxis().set_visible(False)
    plt.show()
    keep_running = input("Make another walk? (y/n): ")
    if keep_running == 'n':
        break

这个运行很好。

这是因为默认情况下 Jupyter 无法在输出单元格上呈现 SVG 图像,因此您需要调整您的代码,使其可被 IPython 控制台读取。您可以执行以下操作:

from IPython.display import HTML, display, SVG
import pygal

while True:
    rw = RandomWalk()
    rw.fill_walk()
    xy_chart = pygal.XY()
    xy_chart.title = 'Random Walk'
    rwValues = list(zip(rw.x_values, rw.y_values))
    xy_chart.add('rw', rwValues)
    keep_running = input("Make another walk? (y/n): ")
    if keep_running == 'n':
        display({'image/svg+xml': xy_chart.render()}, raw=True)
        # OR
        xy_chart.render_in_browser()
        # OR
        display(SVG(xy_chart.render(disable_xml_declaration=True)))
        break

我现在只写了不到 3 个月的代码,但我认为你没看对问题。

它说在 Ploty 上使用 plot Random Walks(离线),我没有使用 pygal,所以我可能会回答一个没人问过的问题,但我还是会做。

既然书中的问题模棱两可,我就告诉你我是怎么做到的。

from random import choice
from plotly.graph_objs import*
from plotly import offline


class RandomWalk:
    '''Generate random walks'''


    def __init__(self,points=5000):

        self.points = points


        #staring point is 0
        self.x_values =[0]
        self.y_values = [0]


    def fill_walk(self):

        '''calculating all of the points in the walk'''

        while len(self.x_values) < self.points:

            x_direction = choice([-1, 1])
            x_distance = choice([0, 3])
            x_step = x_direction * x_distance

            y_direction = choice([-1, 1])
            y_distance = choice([0, 3])
            y_step = y_direction * y_distance

            # reject all moves that go nowhere
            if x_step == 0 and y_step == 0:
                continue

            x = self.x_values[-1] + x_step
            y = self.y_values[-1] + y_step

            self.x_values.append(x)
            self.y_values.append(y)




rw = RandomWalk()
rw.fill_walk()

xa = list(range(rw.points))

frequencies = []

for a_number in (range(1,rw.points)):
    frequency = rw.x_values.count(a_number)
    frequencies.append(frequency)

data = [Bar(x=xa,y=frequencies)]

my_layout = Layout(title="We'll see",xaxis={'title':'X'},yaxis={'title':'Y'})

offline.plot({'data': data,'layout':my_layout},filename='my.html')

显示 y 值变化(频率 = rw.y_values.count(a_number)

我很抱歉代码和评论不足,这是我第一次发帖,但随着时间的推移,我会越来越好