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

如何为Python绘制的条形图添加每个条形上的数值标签

实现代码

你可以直接捕获df.plot()返回的坐标轴对象,遍历所有条形元素添加数值标签,完整可运行代码如下:

import matplotlib.pyplot as plt

# 原有绘图代码,新增变量接收返回的坐标轴对象
ax = df_plot.plot(x ='Pillar', y='%', kind = 'bar', figsize=(9,5))

# 遍历每个条形添加顶部数值标签
for bar in ax.patches:
    bar_height = bar.get_height()
    ax.text(
        # 标签水平位置:条形横向中点
        bar.get_x() + bar.get_width() / 2,
        # 标签垂直位置:条形顶部
        bar_height,
        # 标签显示内容,保留1位小数并加百分号
        f"{bar_height:.1f}%",
        # 对齐方式设置,保证标签居中在条形上方
        ha="center",
        va="bottom"
    )

# 可选优化:调整x轴标签角度避免重叠,自动调整布局
plt.xticks(rotation=30, ha="right")
plt.tight_layout()
plt.show()

核心逻辑说明

  • pandas的plot方法执行后会返回matplotlib的坐标轴(Axes)对象
  • 坐标轴的patches属性存储了所有绘制好的条形元素,遍历即可逐个获取每个条形的位置、高度信息
  • 调用ax.text()方法即可在指定坐标位置添加自定义文本标签

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 15:18:00