首页 > 解决方案 > 如何使用 Python 制作直方图,就像使用 R hist 函数一样

问题描述

我正在尝试在 Python 中制作直方图,就像在 R 中一样。我该怎么做?

回复:

age <- c(43, 23, 56, 34, 38, 37, 41)
hist(age)

R输出

Python:

age = (43, 23, 56, 34, 38, 37, 41)
plt.hist(age)

matplotlib 输出

标签: pythonrmatplotlib

解决方案


这里的差异是由 R 和 matplotlib 默认选择 bin 数量的方式造成的。

对于此特定示例,您可以使用:

age = (43, 23, 56, 34, 38, 37, 41)
plt.hist(age, bins=4)

复制R 风格的直方图

一般情况

如果我们想让 matplotlib 的直方图看起来像一般的 R,我们需要做的就是复制 R 使用的分箱逻辑。在内部,R 使用Sturges 公式* 来计算 bin 的数量。matplotlib 支持这个开箱即用,我们只需要为 bins 参数传递“sturges”。

age = (43, 23, 56, 34, 38, 37, 41)
plt.hist(age, bins='sturges')

* 它内部有点复杂,但这让我们大部分时间都在那里。


推荐阅读