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

如何用plt对x轴排序并为子图条形图添加数值标签

解决x轴排序与条形数值标签问题

1. 数据预处理:确保x轴按a→b→c→d→e排序

有两种高效方式实现有序x轴:

方式一:分组后重索引

对分组聚合结果,通过reindex()强制指定顺序:

# 按id分组求和(可替换为mean/count等其他聚合逻辑)
df1_grouped = df1.groupby('id')['score'].sum().reindex(['a', 'b', 'c', 'd', 'e'])
df2_grouped = df2.groupby('id')['score'].sum().reindex(['a', 'b', 'c', 'd', 'e'])
df3_grouped = df3.groupby('id')['score'].sum().reindex(['a', 'b', 'c', 'd', 'e'])

方式二:将id转为有序分类类型

在分组前把id列设置为有序分类,分组后自动按指定顺序排列:

# 批量为三个DataFrame设置有序分类
for df in [df1, df2, df3]:
    df['id'] = pd.Categorical(df['id'], categories=['a', 'b', 'c', 'd', 'e'], ordered=True)

# 分组求和
df1_grouped = df1.groupby('id')['score'].sum()
df2_grouped = df2.groupby('id')['score'].sum()
df3_grouped = df3.groupby('id')['score'].sum()

2. 绘制子图并添加条形数值标签

创建子图后,绘制条形图并循环为每个条形添加数值标签:

import matplotlib.pyplot as plt

# 创建1行3列的子图,设置画布大小
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 5))

# 处理第一个子图(df1)
bars1 = ax1.bar(df1_grouped.index, df1_grouped.values)
ax1.set_title('df1 分数总和')
ax1.set_xlabel('ID')
ax1.set_ylabel('总分')
# 添加数值标签
for bar in bars1:
    height = bar.get_height()
    ax1.text(bar.get_x() + bar.get_width()/2, height,
             f'{height:.2f}',  # 保留两位小数,可按需调整格式
             ha='center', va='bottom')  # 水平居中、垂直底部对齐

# 处理第二个子图(df2)
bars2 = ax2.bar(df2_grouped.index, df2_grouped.values)
ax2.set_title('df2 分数总和')
ax2.set_xlabel('ID')
for bar in bars2:
    height = bar.get_height()
    ax2.text(bar.get_x() + bar.get_width()/2, height,
             f'{height:.2f}',
             ha='center', va='bottom')

# 处理第三个子图(df3)
bars3 = ax3.bar(df3_grouped.index, df3_grouped.values)
ax3.set_title('df3 分数总和')
ax3.set_xlabel('ID')
for bar in bars3:
    height = bar.get_height()
    ax3.text(bar.get_x() + bar.get_width()/2, height,
             f'{height:.2f}',
             ha='center', va='bottom')

# 自动调整子图间距,避免标签重叠
plt.tight_layout()
plt.show()

可选调整

  • 聚合逻辑:将sum()替换为mean()(求均值)、count()(求样本数)等,适配你的分析需求。
  • 标签格式:修改f'{height:.2f}'为f'{height:.1f}'(一位小数)或f'{int(height)}'(整数)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 08:05:54