使用Pygal模拟掷骰子

在本节中,将使用Python可视化包Pygal来生成可缩放的矢量图形文件。

对于需要在尺寸不同的屏幕上显示的图表,这很有用,因为它们将自动缩放,以适合观看者的屏幕。

1.创建Die类

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)

 

2.分析1000次结果

from die import Die

die=Die()

results=[]
for roll_num in range(1000):
    result=die.roll()
    results.append(result)
    
frequencies=[]
for value in range(1,die.num_sides+1):
    frequency=results.count(value)
    frequencies.append(frequency)
    
print(frequencies)

 

3.绘制直方图

import pygal
from die import Die

die=Die()

results=[]
for roll_num in range(1000):
    result=die.roll()
    results.append(result)
    
frequencies=[]
for value in range(1,die.num_sides+1):
    frequency=results.count(value)
    frequencies.append(frequency)
    
hist=pygal.Bar()
hist.title='Result of rolling one D6 1000 times'
hist.x_labels=['1','2','3','4','5','6']
hist.x_title="Result"
hist.y_title="Frequency of Result"

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

我们将图表渲染为一个SVG文件,使用web浏览器来查看生成的直方图:

 

4.同时掷两个面数不同的骰子50000次

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='Result 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('dice_visual.svg')

 

posted @ 2018-05-08 23:03  Johnny、  阅读(622)  评论(0编辑  收藏  举报