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

如何使用matplotlib在柱状图上为各年份数据标注对应y轴数值

问题修正与实现代码

原有代码的核心问题是标注逻辑和实际数据不匹配,坐标计算规则错误,以下是可直接运行的修正后代码:

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

laikipia = pd.DataFrame({
    "2020":[5.21, 20.91, 17.05],
    "2021":[20.91, 19.91, 19.76],
    }, 
    index=["Cropland", "Forestland", "Shrubland"]
)
c = ['#FFDB5C', '#358221', '#EECFA8']

# 绘图时获取ax对象方便后续操作
ax = laikipia.plot(kind="bar", color=c)
plt.xlabel("Laikipia LULC")
plt.ylabel("Area Loss (ha)")
plt.legend(laikipia, bbox_to_anchor=(1, 1))
plt.xticks(rotation=0)
# 给顶部标注预留10%的空间
plt.ylim(0, laikipia.max().max() * 1.1)

# 遍历所有柱子添加数值标注
for p in ax.patches:
    height = p.get_height()
    # 标注位置对齐柱子水平中心、顶部上方
    ax.text(p.get_x() + p.get_width()/2, height, f'{height:.2f}', 
            ha='center', va='bottom', fontsize=9)

plt.tight_layout()
plt.show()

核心修改说明

  • 移除了和实际数据无关的自定义y轴刻度列表,改为根据实际数值自动适配y轴范围
  • 直接读取pandas绘图返回的ax对象中存储的所有柱子属性,自动获取每个柱子的坐标、高度信息,不需要手动计算位置,可适配任意分组数量的柱状图
  • 修正了plt.text的参数逻辑,标注内容直接从柱子高度属性读取,位置自动对齐柱子中心
  • 调整plt.tight_layout()执行顺序到plt.show()之前,避免图例和标注被裁切

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 08:54:08