数据可视化(四) 摇骰子随机数
①创建一个骰子模拟 die.py
from random import randint
class Dis():
"""表示一个骰子的类"""
def __init__(self,num_sides=6):
"""骰子默认面为6"""
self.num_sides = num_sides
def roll(self):
"""返回一个1到6之间的随机数"""
return randint(1,self.num_sides)
②多次摇一个骰子的数据,进行绘制直方图 die_visual.py
import pygal
from die import Dis
# 创建一个D6
die=Dis()
# 投掷几次骰子,将结果存储在一个列表中
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)
# 对结果进行可视化
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_labels = "Frequency of Result"
hist.add('D6',frequencies)
hist.render_to_file("die_visual.svg")
③同时摇两个骰子的数据进行整理 dice_visual.p
import pygal
from die import Dis
# 创建两个D6
die_1=Dis()
die_2=Dis()
# 投掷几次骰子,将结果存储在一个列表中
results = []
for roll_num in range(1000):
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)
print(frequencies)
# 对结果进行可视化
hist = pygal.Bar()
hist._title = "Result of rolling one D6 1000 times."
hist.x_labels = ['2','3','4','5','6','7','8','9','10','11','12']
hist._x_title = "Result"
hist.y_labels = "Frequency of Result"
hist.add('D6+D6',frequencies)
hist.render_to_file("die_visual.svg")
④同时摇2个面数不同的骰子 different_dice.py
import pygal
from die import Dis
# 创建一个D6和一个D10
die_1=Dis()
die_2=Dis(10)
# 投掷几次骰子,将结果存储在一个列表中
results = []
for roll_num in range(1000):
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)
print(frequencies)
# 对结果进行可视化
hist = pygal.Bar()
hist._title = "Result of rolling one D6 1000 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_labels = "Frequency of Result"
hist.add('D6+10',frequencies)
hist.render_to_file("die_visual.svg")
会产生一个die_visual.svg的整理结果: