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

如何在Matplotlib堆叠柱状图的指定年份柱体上方添加标注?

解决Matplotlib堆叠柱状图annotate无法使用字符串x坐标的问题

Matplotlib绘制柱状图时,x轴显示的字符串标签只是视觉展示,底层实际使用的是数值索引(比如你的四个年份对应的x坐标是0、1、2、3),所以直接传字符串'2021'当x坐标肯定会报错。

解决步骤很简单:

  • 先获取目标年份对应的数值索引:用df.index.get_loc('2021')就能拿到'2021'对应的位置(这里是2)
  • 计算2021年堆叠柱体的总高度,让标注精准放在柱体上方(比硬写350更灵活):df.loc['2021'].sum(),还可以加个小偏移(比如+10)避免和柱体顶边重合

修改后的完整代码:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame()
df['year'] = ['2019','2020','2021','2022']
df = df.set_index('year')
df['test 1'] = [2,16,85,15]
df['test 1a'] = [16,18,9.5,0]
df['test 2'] = [16.5,15,31.5,24]
df['test 3'] = [13.5,34,37,205]
df['test 4'] = [12.5,10,42,96]
df['test 4a'] = [0,44,0,38]
df['test 4b'] = [6,3,8,0]
df['test 4c'] = [0,131,29.5,1]
df['test 5'] = [0,0,87,0]

fig, ax = plt.subplots(1,1,figsize=(9,4))
df.plot(kind='bar', stacked=True, ax=ax)

# 获取2021对应的x数值索引
x_pos = df.index.get_loc('2021')
# 计算2021年堆叠柱的总高度,加10作为偏移
y_pos = df.loc['2021'].sum() + 10
# 标注文本,设置水平居中对齐
ax.annotate(text='revision', xy=(x_pos, y_pos), xycoords='data', ha='center')

plt.show()

关键修改点:

  • 用df.index.get_loc('2021')替换字符串x坐标,拿到底层的数值位置
  • 用柱体总高度+偏移作为y坐标,让标注位置更合理,也适配数据变化
  • 加上ha='center'让文本在x轴位置居中对齐,视觉更美观

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 15:05:43