首页 > 解决方案 > Matplotlib 直方图条未正确放置在每个 bin 中

问题描述

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

在此处输入图像描述

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

标签: pythonmatplotlibhistogram

解决方案


推荐阅读