Matplotlib直方图条未正确放置在每个垃圾箱中

时间:2018-10-25 02:20:32

标签: python matplotlib histogram

我创建了一个程序,可运行100,000次帽子检查问题。它是这样的:

  • 有10个人
  • 每个人在1到10之间(包括1到10)进行随机滚动
  • 如果roll ==他们的索引,则该人“收到”了他的帽子
  • 在每次审判结束时,将戴回帽子的人数添加到列表中
  • 重复进行100,000次
  • 将结果绘制在直方图上,以显示有0个人获得了帽子,有1个人获得了帽子,有2个人,有3个人...有10个人获得了他们的帽子。

enter image description here

不过,正如您在上面的直方图中所看到的那样,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()

0 个答案:

没有答案
相关问题