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

使用Pandas绘制堆叠柱状图时Matplotlib注释文本位置错误求助

解决Pandas堆叠柱状图注释位置不匹配的问题

问题核心:Pandas绘制柱状图时,x轴的实际刻度位置对应DataFrame的行索引(0,1,2...),而非你指定的xval列数值。你直接用xval的值作为注释的x坐标,导致位置完全偏离柱状图。

以下是修正后的代码:

import pandas as pd
from matplotlib import pyplot as plt

data = [
    [0.0, 4.9, 19.9, 8.1, 0.0],
    [0.12, 4.5, 27.0, 10.1, 0.0],
    [0.24, 2.8, 9.3, 4.6, 0.0],
    [0.36, 2.2, 9.1, 2.7, 0.0],
    [0.48, 2.2, 7.3, 3.1, 0.0],
    [1.0, 4.9, 26.4, 11.2, 0.0],
    [1.12, 5.9, 25.3, 8.7, 0.0],
    [1.24, 3.7, 13.3, 7.1, 0.0],
    [1.3599999999999999, 3.0, 9.5, 3.4, 0.0],
    [1.48, 3.2, 8.9, 4.7, 0.0],
    [2.0, 8.4, 24.8, 20.2, 0.0],
    [2.12, 9.5, 19.3, 22.5, 0.0],
    [2.24, 5.7, 11.8, 6.6, 0.0],
    [2.36, 4.1, 11.1, 5.1, 0.0],
    [2.48, 5.4, 8.0, 4.6, 0.0],
]
df = pd.DataFrame(columns=["xval", "y1", "y2", "y3", "y4"], data=data)
df1 = df.copy()
fig, ax = plt.subplots()
df1['total'] = df[['y1','y2','y3','y4']].sum(axis = 1)
df.plot(x="xval", kind="bar", ax=ax, stacked=True, width = 0.11)

# 关键修改:用循环索引i作为注释的x坐标,同时给y坐标加少量偏移避免重叠
for i, row in df1.iterrows():
    ax.annotate(f'{row["xval"]:.1f}-{row["total"]:.1f}', 
                (i, row["total"] + 0.5),  # y轴加0.5偏移
                rotation='vertical', 
                fontsize=10,
                ha='center')  # 水平居中对齐

xticks, ticklabels = zip(*[(i, x) for i, x in enumerate(df["xval"]) if x.is_integer()])
ax.set_xticks(xticks, ticklabels)
ax.grid()
fig.savefig("mychart.png")

关键修改说明:

  • 注释的x坐标使用DataFrame的行索引i,这是柱状图实际对应的x轴位置
  • 给y坐标增加+0.5的偏移,避免注释和柱子顶部重叠
  • 使用iterrows()遍历行,代码更简洁易读
  • 添加ha='center'让注释水平居中于柱子上方

为什么之前的方法无效:

  • annotate的xycoord默认是数据坐标,但柱状图的x数据坐标是行索引,不是xval的数值,所以调整xycoord无法匹配
  • transAxes是轴相对坐标,需要手动计算每个柱子的相对位置,不如直接用行索引精准

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 11:23:20