gpt4 book ai didi

Python Matplotlib pyplot 直方图

转载 作者:行者123 更新时间:2023-12-04 15:23:17 26 4
gpt4 key购买 nike

我正在绘制一个相当简单的模拟的直方图。在直方图上,最后两列合并在一起,看起来很奇怪。请在下面附上代码和绘图结果。

提前致谢!

   import numpy as np
import random
import matplotlib.pyplot as plt

die = [1, 2, 3, 4, 5, 6]
N = 100000
results = []
# first round
for i in range(N):
X1 = random.choice(die)
if X1 > 4:
results.append(X1)
else:
X2 = random.choice(die)
if X2 > 3:
results.append(X2)
else:
X3 = random.choice(die)
results.append(X3)

plt.hist(results)
plt.ylabel('Count')
plt.xlabel('Result');
plt.title("Mean results: " + str(np.mean(results)))
plt.show()

输出看起来像这样。我不明白为什么最后两列粘在一起。

Histogram

感谢任何帮助!

最佳答案

默认情况下,matplotlib 将输入范围划分为 10 个大小相等的 bin。所有 bin 都跨越半开区间 [x1,x2),但最右边的 bin 包括范围的末尾。你的范围是 [1,6],所以你的 bins 是 [1,1.5), [1.5,2), ..., [5.5,6],因此所有整数最终都出现在第一个、第三个等奇数 bin 中,但 6 最终出现在第十个(偶数)bin 中。

要修复布局,请指定容器:

# This will give you a slightly different layout with only 6 bars
plt.hist(results, bins=die + [7])
# This will simulate your original plot more closely, with empty bins in between
plt.hist(results, bins=np.arange(2, 14)/2)

最后一位生成数字序列2,3,...,13,然后将每个数字除以 2,得到 1, 1.5, ..., 6.5 以便最后一个 bin 跨越 [6,6.5]

关于Python Matplotlib pyplot 直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62839204/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com