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

如何在Matplotlib bar()绘制的柱状图柱顶添加标签?

仅用Matplotlib给柱状图顶部添加数值标签的实现方法

你有如下结构的DataFrame:

week          person_counts
2023-01-23    777
2023-01-30    800
2023-02-06    890
2023-02-13    766
2023-02-20    789

要仅用Matplotlib的bar()函数绘制柱状图并在每个柱子顶部添加数值标签,可按以下步骤修改你的代码:

先修正原有代码的两处问题

  1. 语法错误:ax.xaxis.set.major_formatter应为ax.xaxis.set_major_formatter(用下划线连接,而非点)
  2. 列名错误:你的DataFrame日期列是week,不是TimeStamp,需对应调整

完整实现代码

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd

# 构造测试数据(如果已有DataFrame可跳过此段)
data = {
    'week': ['2023-01-23', '2023-01-30', '2023-02-06', '2023-02-13', '2023-02-20'],
    'person_counts': [777, 800, 890, 766, 789]
}
df = pd.DataFrame(data)
df['week'] = pd.to_datetime(df['week'])

# 绘图部分
fig, ax = plt.subplots(figsize=(15, 6))
ax.set_ylabel('Person Count')
ax.set_title('Persons')

# 设置日期格式
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%y'))
# 绘制柱状图,保存返回的BarContainer对象
bars = ax.bar(df['week'], df['person_counts'], width=5)

# 给每个柱子添加顶部数值标签
for bar in bars:
    # 获取柱子高度(即对应person_counts值)
    height = bar.get_height()
    # 在柱子顶部居中位置添加文本
    ax.text(
        bar.get_x() + bar.get_width() / 2,  # x坐标:柱子中心
        height,  # y坐标:柱子顶部
        f'{int(height)}',  # 显示的数值
        ha='center',  # 水平居中
        va='bottom'  # 垂直对齐在柱子顶部下方,避免重叠
    )

plt.xticks(df['week'])
plt.show()

关键逻辑说明

  • ax.bar()函数会返回一个BarContainer对象,包含所有柱子的矩形元素,我们用bars变量保存它
  • 遍历每个柱子时,通过bar.get_height()获取对应数值,bar.get_x()和bar.get_width()计算柱子中心位置
  • 用ax.text()在计算好的位置添加数值文本,通过ha='center'和va='bottom'保证文本对齐美观

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 16:35:24