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

使用barh()绘制水平条形图时的数值标注问题:如何为每个条形显示数值及添加顶部数值?

嘿,这个需求其实挺常见的,用matplotlib的barh()绘制水平条形图时,给每个条形添加对应数值标签非常容易实现。我给你两种常用的实现方式,还有完整的代码示例,你可以直接套用:

方法1:在条形右端(外部)显示数值

这是最常用的方式,数值放在条形的右侧,不会遮挡条形本身:

import matplotlib.pyplot as plt

# 准备你的数据:类别和对应的数值
categories = ['Apple', 'Banana', 'Orange', 'Grape']
values = [45, 32, 58, 29]

# 绘制水平条形图,bars变量会保存每个条形的对象
bars = plt.barh(categories, values)

# 遍历每个条形,添加数值标签
for bar in bars:
    # 获取当前条形的宽度(也就是对应的数值)
    bar_width = bar.get_width()
    # 获取条形的垂直中心位置,确保文本垂直居中
    bar_y_center = bar.get_y() + bar.get_height() / 2
    
    # 添加文本标签:位置在条形右侧偏移1个单位,垂直居中
    plt.text(bar_width + 1, bar_y_center, f'{bar_width}', va='center')

# 调整布局,防止右侧的数值标签被画布边缘截断
plt.tight_layout()
plt.show()

方法2:在条形内部显示数值

如果你的条形足够长,也可以把数值放在条形内部,用对比色(比如白色)让文字更清晰:

import matplotlib.pyplot as plt

categories = ['Apple', 'Banana', 'Orange', 'Grape']
values = [45, 32, 58, 29]

bars = plt.barh(categories, values)

for bar in bars:
    bar_width = bar.get_width()
    bar_y_center = bar.get_y() + bar.get_height() / 2
    
    # 把文本放在条形内部,往左偏移1个单位,文字设为白色
    plt.text(bar_width - 1, bar_y_center, f'{bar_width}', va='center', color='white')

plt.tight_layout()
plt.show()

关键细节说明

  • bar.get_width():直接获取当前条形对应的数值(因为水平条形的宽度就是数值大小)
  • bar.get_y() + bar.get_height()/2:计算条形的垂直中心位置,让文本和条形垂直对齐
  • va='center':设置文本的垂直对齐方式为居中,确保视觉上更协调
  • 偏移量(+1或-1):可以根据你的数据大小调整,确保数值和条形之间的距离合适
  • 数值格式化:如果需要保留小数或添加单位,修改f-string即可,比如f'{bar_width:.2f}'(保留两位小数)或f'{bar_width} kg'(添加单位)

内容的提问来源于stack exchange,提问作者Mahmoud El Mahdy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 09:02:36