python - 如何在 matplotlib 直方图中选择 bin

标签 python python-2.7 matplotlib

谁能解释一下直方图中的“bins”是什么(matplotlib hist 函数)?假设我需要绘制一些数据的概率密度函数,我选择的 bin 如何影响它?我该如何选择它们? (我已经在 matplotlib.pyplot.histnumpy.histogram 库中阅读过它们,但我不明白)

最佳答案

bins 参数告诉您数据将被分成多少个 bin。您可以将其指定为整数或 bin 边缘列表。

例如,这里我们要求 20 个箱子:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.randn(1000)
plt.hist(x, bins=20)

enter image description here

这里我们要求位置 [-4, -3, -2... 3, 4] 的 bin 边缘。

plt.hist(x, bins=range(-4, 5))

enter image description here

您关于如何选择“最佳”数量的垃圾箱的问题是一个有趣的问题,实际上有相当多的关于该主题的文献。已经提出了一些常用的经验法则(例如 Freedman-Diaconis RuleSturges' Rule, Scott's Rule, the Square-root rule 等),每个都有自己的优点和缺点。

如果您想要一个很好的 Python 实现各种这些自动调整直方图规则,您可以查看最新版本的 AstroPy 包中的直方图功能,described here . 这就像 plt.hist 一样工作,但允许您使用类似的语法,例如hist(x, bins='freedman') 用于通过上述 Freedman-Diaconis 规则选择 bin。

我个人最喜欢的是“贝叶斯 block ”(bins="blocks"),它解决了 不等 箱宽度的最佳分箱。您可以阅读更多内容 here .


编辑,2017 年 4 月:使用 matplotlib 2.0 或更高版本和 numpy 1.11 或更高版本,您现在可以直接在 matplotlib 中指定自动确定的 bin,通过指定,例如bins='auto'。这使用了 Sturges 和 Freedman-Diaconis bin 选择的最大值。您可以在 numpy.histogram docs 中阅读有关选项的更多信息。 .

关于python - 如何在 matplotlib 直方图中选择 bin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33458566/

相关文章:

python - 为什么 setuptools 不复制子文件夹中的模块?

python - 从 Flask 路由中的 URL 获取变量

python - 如何对字符串列表中的组件进行分类

Python 坏了,AttributeError : 'module' object has no attribute 'python_version'

python - Matplotlib 图作为新的类属性。稍后如何根据命令显示它?

python - 从包含列表的元组列表中进行字典理解

python - 每隔 n 个位置将列表中的项目插入另一个列表

python - 无效的语法Python Inside打印2.7.11

python - 在 matplotlib 中使用循环变量指定颜色

python matplotlib ax.get_xticks() 无法获取当前 xtick 位置