python - 如何使用 Python 制作直方图,就像使用 R hist 函数一样
问题描述
我正在尝试在 Python 中制作直方图,就像在 R 中一样。我该怎么做?
回复:
age <- c(43, 23, 56, 34, 38, 37, 41)
hist(age)
Python:
age = (43, 23, 56, 34, 38, 37, 41)
plt.hist(age)
解决方案
这里的差异是由 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')
* 它内部有点复杂,但这让我们大部分时间都在那里。
推荐阅读
- xpath - BaseX XQuery 命令获取 XML 文件名
- apache-spark - 在 Spark SQL 中查询数组结构列
- php - 如何使用 PHP 在 Laravel 7 中将 PascalCase 字符串转换为可用的 slug?
- windows - Windows Docker 安装 oracle 数据库
- ansible - Ansible 错误是:'unicode object'没有属性
- reactjs - 我应该如何使用 react-route-dom 函数来创建子路由
- php - 如何在 h 中分配变量
- json - 如何在一个字符串参数中拆分两个json
- c# - 获取多边形内的点x距离
- java - Windows 10打包java应用,打开JDK 11