python - Matplotlib 直方图条未正确放置在每个 bin 中
问题描述
我创建了一个运行帽子检查问题 100,000 次的程序。它是这样工作的:
- 有10个人
- 每个人在1-10(含)之间滚动一个随机数
- 如果 roll == 他们的索引,那么那个人会“收到”他的帽子
- 在每次试验结束时,将帽子归还的人数附加到列表中
- 试验重复 100,000 次
- 结果绘制在直方图上,以显示有多少 0 人收到了他们的帽子,1 人收到了帽子,2 人,3 人...... 10 人收到了他们的帽子。
正如您在上面的直方图中看到的那样,x 轴标签不在每个条的中间。此外,2 和 3 之间存在不应该存在的差距。
为什么是这样??
代码:
import matplotlib.pyplot as plt
from random import randint
# Define constant N for number of people
N = 10
# Define constant E for number of experiments
E = 100000
# Define list of number of ppl who got their hat back after each experiment
trials = []
# Run experiement E times
for i in range(E):
# Initialise r as number of people who had their hat returned
r = 0
# Loop through each person in N
for i in range(1, N+1):
# Each person rolls a random number
roll = randint(1, 10)
# If roll equals to i, then ith person received his hat back. So increment r by 1
if roll == i:
r += 1
# Append how many ppl got their hat returned after each trial
trials.append(r)
print(trials)
# Create histogram
plt.hist(trials, 10, rwidth=0.8)
# Show histogram
plt.show()
解决方案
推荐阅读
- macos - NSCollectionView,与组合布局左对齐
- php - 需要一个 wp all export 函数来反序列化特定字段的数据
- nestjs - 如何返回新创建的实体及其与 Nest.js/TypeORM 的关系?
- ios - 使用存储在参数中的类型转换对象
- c++ - C++ 和 CLion - 特定于平台的代码有问题
- javascript - 带有 Vue 路由器的 Vue 3:路由器链接具有正确的 Vue 参数,但未反映在 HTML 中
- java - 在 Java 中删除包含单元格“NULL”的 csv 格式的行
- python - 根据其他列中的值限制多个数据框列
- c++ - 未解析的外部符号 __tzname Perforce 库
- ssas - 以下哪个 MDX 语法最“正确”?