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

如何在Matplotlib柱状图中为特定柱状条(非全部)添加标签?

问题描述

我已绘制出展示一年中每日数据计数的Matplotlib柱状图,希望仅为特定日期(例如11月24日感恩节)的柱状条添加标签,但目前仅找到为全部柱状条添加标签的示例。我的代码如下:

daychart = data.groupby(['Day'], as_index=False, sort=False).agg(Count=('Day','size'))
plt.figure(figsize=(20,4))
matplotlib.pyplot.bar(x="Day", height="Count", data=daychart)
plt.show()

当前图表样式如图所示:
一年每日数据计数柱状图
请问该如何实现仅为特定日期柱状条添加标签?

解决方案

实现步骤

  1. 保存柱状条对象:调用bar()方法时捕获返回的BarContainer实例,它包含所有柱状条的信息。
  2. 定位目标日期索引:从处理后的daychart数据中筛选出目标日期对应的行索引。
  3. 单独添加标签:使用annotate()方法仅对目标索引的柱状条添加文本标签。

修改后的代码示例

import matplotlib.pyplot as plt

# 原数据处理逻辑
daychart = data.groupby(['Day'], as_index=False, sort=False).agg(Count=('Day','size'))

plt.figure(figsize=(20,4))
# 保存所有柱状条对象
bars = plt.bar(x="Day", height="Count", data=daychart)

# 设定目标日期(需与daychart['Day']的格式完全匹配)
target_date = "202X-11-24"
# 获取目标日期对应的索引
target_idx = daychart[daychart['Day'] == target_date].index[0]

# 为目标柱状条添加标签
target_bar = bars[target_idx]
bar_height = target_bar.get_height()
plt.annotate(f'计数: {bar_height}',
             xy=(target_bar.get_x() + target_bar.get_width()/2, bar_height),
             xytext=(0, 5),  # 标签在柱顶上方5像素处
             textcoords="offset points",
             ha='center', fontsize=10)

plt.show()

注意事项

  • 必须保证target_date的格式和daychart['Day']中的日期格式完全一致,否则无法匹配到目标行。
  • 可根据需求调整annotate()的参数,比如xytext控制标签偏移距离,fontsize调整标签字号。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 04:40:27