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

Pandas绘制多组直方图:Y轴标签设置及图表异常问题排查

问题分析

你的代码存在两个核心问题:

  • df.hist(by='group')会按group拆分生成多张独立子图,无法实现同图展示多组数据的需求
  • pandas的hist()方法默认统计value列的出现频数,而非使用你提供的count列数值作为直方图高度,导致Y轴数值完全不符合预期
正确实现方式

方法1:用Matplotlib手动绘制同图分组柱状图

你的value是离散固定值,用柱状图更贴合数据特性,同时能把三组数据放在同一张图中:

import matplotlib.pyplot as plt
import pandas as pd

d = {'group': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'D', 'D', 'D', 'D', 'D'], 
     'value': [0.2, 0.4, 0.6, 0.8, 0.2, 0.4, 0.6, 0.8, 0.2, 0.4, 0.6, 0.8, 1.0],
     'count': [4, 3, 7, 3, 12, 14, 5, 10, 3, 8, 7, 15, 4]}
df = pd.DataFrame(data=d)

# 设置X轴偏移量,避免柱状图重叠
x_offset = 0.2
groups = df['group'].unique()
x_values = df['value'].unique()

fig, ax = plt.subplots()

for i, group in enumerate(groups):
    group_data = df[df['group'] == group]
    # 为每组数据设置偏移后的X轴位置
    x_pos = [x + i*x_offset for x in range(len(x_values))]
    ax.bar(x_pos, group_data['count'], width=x_offset, label=group)

# 配置X轴刻度与标签
ax.set_xticks([x + x_offset for x in range(len(x_values))])
ax.set_xticklabels(x_values)
ax.set_xlabel('value')
ax.set_ylabel('count')
ax.legend(title='Group')
plt.show()

方法2:用Seaborn快速实现分组柱状图

Seaborn的barplot可以更简洁地完成同图分组展示:

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

d = {'group': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'D', 'D', 'D', 'D', 'D'], 
     'value': [0.2, 0.4, 0.6, 0.8, 0.2, 0.4, 0.6, 0.8, 0.2, 0.4, 0.6, 0.8, 1.0],
     'count': [4, 3, 7, 3, 12, 14, 5, 10, 3, 8, 7, 15, 4]}
df = pd.DataFrame(data=d)

sns.barplot(data=df, x='value', y='count', hue='group', width=0.8)
plt.xlabel('value')
plt.ylabel('count')
plt.legend(title='Group')
plt.show()

若需绘制直方图(连续值区间统计)

如果确实要将value视为连续值,按区间统计并以count为权重,可使用以下代码:

import matplotlib.pyplot as plt
import pandas as pd

d = {'group': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'D', 'D', 'D', 'D', 'D'], 
     'value': [0.2, 0.4, 0.6, 0.8, 0.2, 0.4, 0.6, 0.8, 0.2, 0.4, 0.6, 0.8, 1.0],
     'count': [4, 3, 7, 3, 12, 14, 5, 10, 3, 8, 7, 15, 4]}
df = pd.DataFrame(data=d)

fig, ax = plt.subplots()

for group in df['group'].unique():
    group_data = df[df['group'] == group]
    # 用count列作为权重绘制直方图
    ax.hist(group_data['value'], weights=group_data['count'], bins=5, alpha=0.5, label=group)

ax.set_xlabel('value')
ax.set_ylabel('count')
ax.legend(title='Group')
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 03:46:04