要求通过Matplotlib可视化来模拟掷骰子
代码如下:
from random import randint
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams['font.sans-serif'] = ['Microsoft YaHei'] # 指定默认字体
class Die:
def __init__(self, num_sides=6):
self.num_sides = num_sides
def roll(self):
return randint(1, self.num_sides)
#收集数据
die_1 = Die()
die_2 = Die()
results = [die_1.roll() + die_2.roll() for roll_num in range(1_000_000)]
#分析数据
max_result = die_1.num_sides + die_2.num_sides
frequencies = [results.count(value) for value in range(2, max_result+1)]
#可视化结果
x_values = list(range(2, max_result+1))
y_values = frequencies
plt.style.use('Solarize_Light2')
fig, ax = plt.subplots()
ax.bar(x_values, y_values)
ax.set_title("掷2个D6 1_000_000次的结果", fontsize=14)
ax.set_xlabel("结果", fontsize=14)
ax.set_ylabel("结果的频率", fontsize=14)
plt.xticks(x_values)
plt.show()