安装库
这里我们使用可视化包pygal模拟骰子
pygal画廊
具体图表类型画廊可访问Chart types — pygal 2.0.0 documentation
每个实例都有源代码
创建Die类
1 2 3 4 5 6 7 8 9 10 11 12
| from random import randint
class Die(): """表示一个骰子的类"""
def __init__(self,num_sides=6): """骰子默认是6面""" self.num_sides=num_sides
def roll(self): """返回1到6之间的随机数""" return randint(1,self.num_sides)
|
6面骰子我们叫D6,8就是D8
掷骰子
循环100次并将值result存入results列表中
1 2 3 4 5 6 7 8 9 10 11 12
| from die import Die
die = Die()
results = [] for roll_num in range(100): result = die.roll() results.append(result)
print(results)
|
分析数据
我们这里使用方法count统计每一种点数出现的次数,并将掷骰子次数加到1000
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| 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)
|
绘制直方图
这里就可以用上我们的pygal库了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| from die import Die import pygal
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 = "Results of rolling one D6 1000 times" hist.x_labels = ["1","2","3","4","5","6"] hist.x_title = "Result" hist.y_title = "Frenquency of Result"
hist.add('D6',frequencies)
hist.render_to_file('die_visual.svg')
|
最后生成的svg文件用浏览器打开就行