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

如何用matplotlib的hist()函数绘制分箱数据的直方图?

问题

你手头有分箱格式的Level和Quantity数据(字符串形式的区间),尝试用plt.hist()绘制直方图时失败——Matplotlib无法识别字符串类型的分箱区间。

原始数据示例:

Level              Quantity
0      (199.533, 271.74]  (10.213, 39.4]
1      (199.533, 271.74]  (10.213, 39.4]
2      (54.903, 127.327]  (10.213, 39.4]
...                  ...             ...

你尝试的代码无法工作,核心原因是plt.hist()需要数值型数据,而非字符串区间。

解决步骤

1. 解析分箱字符串为数值

首先要把每个分箱区间转换成可用于统计的数值,最常用的方式是提取区间中点(也可以选择左/右边界,按需调整)。

编写解析函数:

def get_bin_midpoint(bin_str):
    # 移除括号/方括号,分割出上下限
    bin_str = bin_str.replace('(', '').replace(']', '')
    lower, upper = map(float, bin_str.split(','))
    return (lower + upper) / 2

2. 处理DataFrame数据

将解析函数应用到Level和Quantity列,生成对应的数值列:

import pandas as pd
import matplotlib.pyplot as plt

# 你的原始数据
data = {
    'Level': ['(199.533, 271.74]', '(199.533, 271.74]', '(54.903, 127.327]', '(127.327, 199.533]', '(127.327, 199.533]'],
    'Quantity': ['(10.213, 39.4]', '(10.213, 39.4]', '(10.213, 39.4]', '(10.213, 39.4]', '(10.213, 39.4]']
}
df_binned = pd.DataFrame(data)

# 生成区间中点列
df_binned['Level_mid'] = df_binned['Level'].apply(get_bin_midpoint)
df_binned['Quantity_mid'] = df_binned['Quantity'].apply(get_bin_midpoint)

3. 绘制直方图

现在有两种绘制方式可选:

方式一:用中点数值绘制直方图

适合需要展示数值分布的场景:

# Level直方图
plt.figure(figsize=(10, 5))
plt.hist(df_binned['Level_mid'], bins=3, edgecolor='black', alpha=0.7)
plt.title('Level 分箱直方图')
plt.xlabel('Level 区间中点')
plt.ylabel('频率')
plt.show()

# Quantity直方图
plt.figure(figsize=(10, 5))
plt.hist(df_binned['Quantity_mid'], bins=2, edgecolor='black', alpha=0.7)
plt.title('Quantity 分箱直方图')
plt.xlabel('Quantity 区间中点')
plt.ylabel('频率')
plt.show()

方式二:直接统计分箱频率绘制柱状图

适合保留原始分箱标签展示的场景,避免直方图自动重新分箱的问题:

# Level分箱频率统计
level_counts = df_binned['Level'].value_counts().sort_index()

plt.figure(figsize=(10, 5))
level_counts.plot(kind='bar', edgecolor='black', alpha=0.7)
plt.title('Level 分箱频率')
plt.xlabel('Level 区间')
plt.ylabel('出现次数')
plt.xticks(rotation=45)
plt.show()

# Quantity分箱频率统计
quantity_counts = df_binned['Quantity'].value_counts().sort_index()

plt.figure(figsize=(10, 5))
quantity_counts.plot(kind='bar', edgecolor='black', alpha=0.7)
plt.title('Quantity 分箱频率')
plt.xlabel('Quantity 区间')
plt.ylabel('出现次数')
plt.xticks(rotation=45)
plt.show()
关键提示
  • plt.hist()的核心逻辑是处理数值型数据,因此必须将字符串分箱转换为数值(中点/边界)才能使用。
  • 如果需要保留原始分箱的文字标签,用value_counts()统计后绘制柱状图是更精准的选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 14:56:34