You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib绘制直方图时柱状高度计算错误问题排查

直方图分箱不符合预期的问题修复

我从CSV读取数据后,按Sturges规则算出分箱数为5,用Matplotlib绘制直方图,但结果和预期不符。

现有代码

import matplotlib.pyplot as plot

height = [167, 170, 173, 173, 173, 174, 175, 178, 180, 180, 182, 182, 184, 185, 187, 188, 189, 190, 192, 193, 195, 197, 199, 202]
plot.hist(height, bins=5)
plot.xlabel("Sizes")
plot.ylabel("Count")
plot.show()

预期分箱及计数

167 - 174.0: 6
174.0 - 181.0: 4
181.0 - 188.0: 6
188.0 - 195.0: 5
195.0 - 202.0: 3

问题原因及修复方案

问题原因

Matplotlib的hist函数在仅指定bins=N时,会默认从数据的最小值到最大值等宽划分N个区间,但这个逻辑和你预期的「从167开始、步长为7的自定义区间」不一致,导致结果不符。

修复代码

手动指定分箱边界列表,替换原有的bins=5参数即可:

import matplotlib.pyplot as plot

height = [167, 170, 173, 173, 173, 174, 175, 178, 180, 180, 182, 182, 184, 185, 187, 188, 189, 190, 192, 193, 195, 197, 199, 202]
# 手动设置预期的分箱边界
bins = [167, 174, 181, 188, 195, 202]
# 加上edgecolor参数可以更清晰区分每个区间
plot.hist(height, bins=bins, edgecolor='black')
plot.xlabel("Sizes")
plot.ylabel("Count")
plot.show()

补充说明

Sturges规则公式为k = 1 + log2(n),其中n是数据量。这里n=24,计算得k≈5.58,取整为5,但该规则仅提供分箱数量,不指定区间的起始值和步长。你预期的区间刚好是基于数据最小值167,步长(202-167)/5=7的等宽区间,因此手动指定边界就能完全匹配预期结果。

内容的提问来源于stack exchange,提问作者Yubi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 13:25:33