热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Python3学习笔记(十二)生成数据

Python3学习笔记(十二)生成数据参考书籍《Python编程:从入门到实践》【美】EricMatthes数字的三次方被称为其立方。请绘制一个图形,显示前5000个整数的立方值

Python3 学习笔记(十二)生成数据

参考书籍《Python编程:从入门到实践》【美】Eric Matthes

数字的三次方被称为其立方。请绘制一个图形,显示前5000个整数的立方值

import matplotlib.pyplot as plt

x_values = list(range(1, 5001))
y_values = [value**3 for value in x_values]

plt.scatter(x_values, y_values)

plt.tick_params(axis='both', labelsize=14)

plt.show()

给你前面绘制的立方图指定颜色映射。

import matplotlib.pyplot as plt

x_values = list(range(1, 5001))
y_values = [value**3 for value in x_values]

plt.scatter(x_values, y_values, c='red')

plt.tick_params(axis='both', labelsize=14)

plt.show()

模拟随机漫步

#random_walk.py
from random import choice

class RandomWalk():

    def __init__(self, num_points=5000):
        self.num_points = num_points

        self.x_values = [0]
        self.y_values = [0]

    def fill_walk(self):
        while len(self.x_values) 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

            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
import matplotlib.pyplot as plt

from random_walk import RandomWalk

while True:
    rw = RandomWalk(5000)
    rw.fill_walk()

    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.Blues, edgecolors='none', s=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

修改rw_visual.py,将其中的plt.scatter() 替换为plt.plot() 。为模拟花粉在水滴表面的运动路径,向plt.plot() 传递rw.x_values和rw.y_values ,并指定实参值linewidth 。使用5000个点而不是50 000个点。

#rw_visual.py
import matplotlib.pyplot as plt

from random_walk import RandomWalk

while True:
    rw = RandomWalk()
    rw.fill_walk()

    plt.figure(figsize=(10, 6))

    point_numbers = list(range(rw.num_points))
    plt.plot(rw.x_values, rw.y_values, linehljs-number">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

方法fill_walk() 很长。请新建一个名为get_step() 的方法,用于确定每次漫步的距离和方向,并计算这次漫步将如何移动。然后,在fill_walk() 中调用get_step() 两次:

#random_walk.py
from random import choice

class RandomWalk():

    def __init__(self, num_points=5000):
        self.num_points = num_points

        self.x_values = [0]
        self.y_values = [0]

    def fill_walk(self):
        while len(self.x_values) 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)

    def get_step(self):
        direction = choice([1, -1])
        distance = choice([0, 1, 2, 3, 4])
        step = direction * distance
        return step

模拟掷骰子

#die.py
from random import randint

class Die():

    def __init__(self, num_sides=6):
        self.num_sides = num_sides

    def roll(self):
        return randint(1, self.num_sides)
#dice_visual.py
import pygal

from die import Die

die_1 = Die()
die_2 = Die(10)

results = []
for roll_num in range(50000):
    result = die_1.roll() + die_2.roll()
    results.append(result)

frequencies = []
max_result = die_1.num_sides + die_2.num_sides
for value in range(2, max_result + 1):
    frequency = results.count(value)
    frequencies.append(frequency)

hist = pygal.Bar()

hist.title = "Results of rolling a D6 and a D10 50000 times."
hist.x_labels = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16']
hist.x_title = "Result"
hist.y_title = "Frequency of Result"

hist.add('D6 + D10', frequencies) 
hist.render_to_file('die_visual.svg')

请修改die.py和dice_visual.py,将用来设置hist.x_labels 值的列表替换为一个自动生成这种列表的循环。如果你熟悉列表解析,可尝试将die_visual.py和dice_visual.py中的其他for 循环也替换为列表解析。

#dice_visual.py
import pygal

from die import Die

die_1 = Die()
die_2 = Die(10)

results = [die_1.roll() + die_2.roll() for roll_num in range(50000)]

max_result = die_1.num_sides + die_2.num_sides
frequencies = [results.count(value) for value in range(2, max_result + 1)]

hist = pygal.Bar()

hist.title = "Results of rolling a D6 and a D10 50000 times."
hist.x_labels = list(range(2, max_result + 1))
hist.x_title = "Result"
hist.y_title = "Frequency of Result"

hist.add('D6 + D10', frequencies) 
hist.render_to_file('die_visual.svg')


推荐阅读
author-avatar
青末老大_660
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有