下面是一个使用Python绘制投掷两个骰子的点数和的直方图的示例代码:
import random
import matplotlib.pyplot as plt
# 模拟投掷两个骰子,并计算点数和
def throw_dice():
dice_1 = random.randint(1, 6)
dice_2 = random.randint(1, 6)
return dice_1 + dice_2
# 模拟投掷1000次,并记录点数和的结果
results = []
for _ in range(1000):
result = throw_dice()
results.append(result)
# 绘制直方图
plt.hist(results, bins=range(2, 14), density=True, rwidth=0.8)
# 设置图表标题和坐标轴标签
plt.title("Histogram of Sum of Two Dice")
plt.xlabel("Sum")
plt.ylabel("Frequency")
# 显示图表
plt.show()
此代码使用了random
模块来模拟投掷两个骰子,并计算点数和。然后,使用matplotlib.pyplot
模块绘制了直方图,其中hist
函数用于绘制直方图,bins
参数指定了直方图的箱子范围(从2到13),density
参数设置为True
表示将频率归一化,rwidth
参数设置为0.8表示调整直方图的宽度。
最后,使用title
、xlabel
和ylabel
函数设置了图表的标题和坐标轴标签,并使用show
函数显示图表。