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

如何绘制X轴分箱数为10、Y轴为Type列A类占比的直方图

实现代码

import pandas as pd
import matplotlib.pyplot as plt

# 原始数据
df = pd.DataFrame([['A', 4], ['B', 12], ['B', 50], ['B', 19], ['A', 39], ['B', 12], ['A', 22], ['B', 33], ['B', 14], ['B', 43], ['A', 50], ['B', 34], ['A', 22],  ['B', 60],
              ['A', 14], ['B', 31], ['B', 40], ['B', 38], ['A', 21], ['B', 41], ['A', 23], ['B', 45], ['B', 25], ['B', 32], ['A', 10], ['B', 31], ['A', 21],  ['B', 51]])
df.columns = ['Type', 'Distance']

# 1. 生成间隔为10的整数分箱,左闭右开区间匹配示例计算逻辑
df['bin'] = pd.cut(df['Distance'], bins=range(0, 70, 10), right=False)

# 2. 按分箱分组计算A类占比
def calc_a_ratio(group):
    a_count = (group['Type'] == 'A').sum()
    total_count = len(group)
    return a_count / total_count * 100 if total_count > 0 else 0

ratio_df = df.groupby('bin', observed=True).apply(calc_a_ratio).reset_index(name='a_ratio')

# 3. 格式化X轴标签为纯整数区间,避免浮点格式
ratio_df['bin_label'] = ratio_df['bin'].apply(lambda x: f"{int(x.left)}-{int(x.right)}")

# 4. 绘制直方图
plt.figure(figsize=(10, 6))
plt.bar(ratio_df['bin_label'], ratio_df['a_ratio'], width=0.8)
plt.xlabel('距离分箱')
plt.ylabel('A类占比(%)')
plt.title('各距离分箱内A类数量占比')
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()

逻辑说明

  • 分箱参数right=False设置为左闭右开规则,和你示例中10-20分箱包含10、不包含20的计算逻辑完全匹配
  • 最终X轴显示为0-10、10-20这类纯整数区间标签,无浮点格式
  • 空分箱默认返回占比0,你可以根据需求调整calc_a_ratio函数的空值处理逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 12:54:03