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

如何用Matplotlib绘制指定区间的等宽长尾分布直方图?

解决Matplotlib长尾分布直方图条形宽度不均的问题

你的问题根源在于:Matplotlib默认的hist函数会按照数值区间的实际宽度分配条形宽度,而你需要的是自定义分类区间的等宽条形。直接用hist处理不等距区间时,窄区间的条形自然会被压缩得很窄。

解决思路是:手动统计每个自定义区间的频数,用bar图(分类条形图)代替hist图,强制每个条形宽度一致。

具体实现代码

import matplotlib.pyplot as plt
import numpy as np

# 原始数据
data = [0] * 100 + list(range(1,6)) * 20 + list(range(6,26)) * 5 + list(range(26, 125))

# 定义自定义区间边界(偏移0.5确保数值被正确归类)
bins = [-0.5, 0.5, 5.5, 25.5, 125.5]
# 对应的区间标签
range_labels = ['0', '1-5', '6-25', '26-125']

# 统计每个区间的频数
counts, _ = np.histogram(data, bins=bins)

# 绘制等宽条形图
plt.figure(figsize=(8, 5))
bars = plt.bar(range(len(range_labels)), counts, width=0.8, color='#1f77b4')

# 设置x轴刻度为自定义标签
plt.xticks(range(len(range_labels)), range_labels)

# 在条形上方标注具体频数(可选,提升可读性)
for bar in bars:
    height = bar.get_height()
    plt.text(bar.get_x() + bar.get_width()/2., height,
             f'{height}',
             ha='center', va='bottom')

# 图表基础设置
plt.title('长尾分布数据统计')
plt.xlabel('数值范围')
plt.ylabel('频数')

plt.tight_layout()
plt.show()

关键细节说明

  1. 区间边界设置:给每个目标范围加±0.5的偏移(比如[-0.5, 0.5]对应0),确保单个数值或连续区间的边界值被正确归类,不会出现漏统计或重复统计。
  2. 用bar代替hist:bar图基于分类索引绘制,所有条形默认等宽,完全规避了hist按数值区间宽度分配条形宽度的问题。
  3. 频数统计:借助np.histogram自动计算每个区间的数量,比手动遍历统计更高效准确。

内容的提问来源于stack exchange,提问作者Jonas De Schouwer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 09:57:23