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

Pandas堆叠柱状图如何为不同层级柱子添加指定数值与占比标签

实现代码

import pandas as pd
import matplotlib.pyplot as plt

# 原始数据
d = {'X':[1,2,3,4],'A': [50,40,20,60], '% of Total in A':[29.4,23.5,11.8,35.3] , 'B': [25,10,5,15], '% in A' :[50,25,25,25]}
df = pd.DataFrame(d)

# 绘制堆叠柱状图,指定颜色和堆叠参数
ax = df.plot(x='X', y=['A', 'B'], kind='bar', stacked=True, color=['C0', 'C2'])

# 获取所有柱子对象,前4个为A列柱子,后4个为B列柱子
bars = ax.patches

# 标注A列柱子的顶部标签
for i in range(4):
    bar = bars[i]
    height = bar.get_height()
    # 标注位置:柱子水平中心,柱子顶部上方一点
    ax.text(
        bar.get_x() + bar.get_width()/2,
        height + 1, # 偏移量可根据实际绘图尺寸调整,避免标签贴到柱子上
        f"{df.loc[i, 'A']} ({df.loc[i, '% of Total in A']}% of the total)",
        ha='center', va='bottom'
    )

# 标注B列柱子的顶部标签(在A柱内部)
for i in range(4, 8):
    df_idx = i - 4
    bar = bars[i]
    height = bar.get_height()
    # 标注位置:柱子水平中心,B柱顶部
    ax.text(
        bar.get_x() + bar.get_width()/2,
        bar.get_y() + height + 0.5, # 小幅偏移避免贴柱
        f"{df.loc[df_idx, 'B']} ({df.loc[df_idx, '% in A']}% in group)",
        ha='center', va='bottom'
    )

# 调整y轴上限,避免顶部标签被截断
ax.set_ylim(0, df['A'].max() + 10)

plt.show()

关键逻辑说明

  • 堆叠柱状图的所有柱体都存储在ax.patches属性中,顺序和绘图时传入的列顺序、行顺序一致,本例中前4个是A列对应X=14的柱子,后4个是B列对应X=14的柱子
  • ax.text()用于添加自定义文本标签,ha='center'保证文本在柱子水平方向居中,va参数控制垂直对齐方式
  • 数值偏移量可以根据自己的绘图尺寸灵活调整,避免标签和柱子重叠

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 15:36:02