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

如何使用plt.bar_label()选择性地为柱状图添加标签?

仅为柱状图子集添加标签的实现方法

可以直接对bars对象进行切片操作,因为plt.bar()返回的BarContainer实例包含的patches属性是支持切片的可迭代序列,通过bars[:3]就能选中前三个柱状图元素,配合对应的标签子集即可实现仅为目标柱状图添加标签,完全不需要调用plt.text()或plt.annotate()。

修改后的示例代码

# 导入库
import matplotlib.pyplot as plt
import pandas as pd

# 测试数据
values = [10, 9, 10.5, 4, 3.1, 2]
labels = [
    'sensor calibration', 'sensor response', 'noise floor estimate',
    'noise floor theta', 'weighted response coef', 'linear estimate'
]

# 创建柱状图
ax = plt.figure(figsize=(5, 2)).add_subplot()
bars = ax.bar(range(6), values, color='lightgray')
ax.set(xlabel='x', ylabel='value', title='Data')
ax.spines[['top', 'right']].set_visible(False)

# 仅为前三个柱状图添加标签
label_kwargs = dict(rotation=90, weight='bold', fontsize=8, label_type='center')
# 对bars和labels都取前三个子集
ax.bar_label(bars[:3], labels[:3], **label_kwargs)

plt.show()

关键说明

  • bars[:3]提取了BarContainer中的前3个柱状图元素,传递给bar_label后,方法只会为这些指定元素添加标签
  • 同步传入labels[:3]作为对应标签文本,保证标签与目标柱状图一一匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 04:45:58