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

如何在Matplotlib直方图中直接将柱高除以指定值展示平均值?

直接用plt.hist实现直方图柱高度求平均的方法

当然可以直接通过Matplotlib的plt.hist实现,不用提前手动统计数值出现次数再做除法!这里有两种简洁的方式,其中一种完全符合你“一步到位”的需求:

方法一:利用weights参数直接计算平均值(推荐)

这是最直接的方式——通过给每个数据点设置权重,让plt.hist直接输出你想要的平均值结果。原理很简单:每个数据点的权重设为1/指定除数,这样直方图每个柱的高度就是该区间内数据点的数量除以除数,也就是你要的平均值。

示例代码:

import matplotlib.pyplot as plt

# 替换成你的实际数据
cluster_1bo = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5]
num_bins = [1,2,3,4,5,6,7,8,9]
divisor = 100  # 你指定的除数

# 带weights参数的直方图绘制
n, bins, patches = plt.hist(
    cluster_1bo,
    num_bins,
    density=False,
    facecolor='g',
    alpha=0.75,
    weights=[1/divisor] * len(cluster_1bo)  # 每个数据点贡献1/divisor的权重
)

plt.xlabel('Bins')
plt.ylabel('Average Count')
plt.title('Histogram with Average Height')
plt.grid(axis='y', alpha=0.75)
plt.show()

运行这段代码后,直方图的每个柱高度就是对应区间的频次除以100后的平均值,完全不需要额外的统计步骤。

方法二:绘制后修改柱高度

如果你已经绘制了原始直方图,也可以直接遍历返回的patches对象修改每个柱的高度,同时调整y轴范围避免显示问题:

import matplotlib.pyplot as plt

cluster_1bo = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5]
num_bins = [1,2,3,4,5,6,7,8,9]
divisor = 100

# 先绘制原始直方图
n, bins, patches = plt.hist(cluster_1bo, num_bins, density=False, facecolor='g', alpha=0.75)

# 逐个修改柱高度
for patch in patches:
    original_height = patch.get_height()
    patch.set_height(original_height / divisor)

# 调整y轴范围,确保所有柱都能完整显示
plt.ylim(0, max(n)/divisor * 1.1)
plt.ylabel('Average Count')
plt.title('Modified Histogram with Average Height')
plt.grid(axis='y', alpha=0.75)
plt.show()

两种方法都能达到你的需求,其中方法一更高效,不需要额外的遍历修改步骤,完全通过plt.hist的参数实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 10:12:33