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

如何对直径数据分箱计数并归一化Y轴以绘制图表?

解决直径分箱、统计与归一化绘图问题

1. 导入依赖库

import pandas as pd
import matplotlib.pyplot as plt

2. 构建数据集

# 按给定数据创建DataFrame
data = {
    'DIAMETER': [3.039085, 2.763617, 2.052176, 9.498093, 2.680360],
    'AREA': [1230000]*5
}
df = pd.DataFrame(data)

3. 定义分箱规则

要生成2-3到9-10间隔为1的分箱,先设定边界和对应标签:

# 分箱边界:2到10,左闭右开
bins = range(2, 11)
# 生成分箱标签,如2-3、3-4...
labels = [f"{i}-{i+1}" for i in bins[:-1]]

4. 分箱并统计数量

使用pd.cut完成分箱,开启include_lowest=True确保左边界值(如2.05)被正确归入2-3箱;之后统计各箱数量,并用reindex补全所有分箱标签(缺失的箱计数补0):

# 给直径列打箱标签
df['bin'] = pd.cut(df['DIAMETER'], bins=bins, labels=labels, include_lowest=True)

# 统计各箱数量,补全所有分箱(确保空箱显示0)
bin_counts = df['bin'].value_counts().reindex(labels, fill_value=0)

此时bin_counts的输出符合你需要的格式:

2-3     3
3-4     1
4-5     0
5-6     0
6-7     0
7-8     0
8-9     0
9-10    1
Name: bin, dtype: int64

5. 归一化处理

所有样本的面积都是1230000,直接用计数除以该值完成归一化:

normalized_counts = bin_counts / df['AREA'].iloc[0]

如果后续数据中面积存在差异,可按分组统计后再做归一化。

6. 绘制图表

用柱状图展示分箱与归一化计数的关系:

plt.figure(figsize=(10, 6))
normalized_counts.plot(kind='bar', color='#4287f5')
plt.xlabel('直径分箱')
plt.ylabel('归一化计数')
plt.title('直径分箱归一化计数分布')
plt.xticks(rotation=0)  # 保持X轴标签水平,提升可读性
plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 12:10:17