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

使用Matplotlib的bar_label为水平条形图添加标签

在Matplotlib水平条形图上添加数值标签的解决方案

嗨,我来帮你搞定这个水平条形图加数值标签的问题~其实核心就是要正确获取条形图的容器对象,再调用bar_label方法就行,我给你调整好代码,你可以直接用:

方法一:直接使用pyplot接口

import pandas as pd
import matplotlib.pyplot as plt

# 准备并排序数据
df = pd.DataFrame({
    "coins": ["BTC", "ETH", "BNB", "XRP", "SOL", "ADA"],
    "dominance": [42.08, 19.38, 3.68, 1.73, 1.55, 1.51]
})
df = df.sort_values(by=["dominance"])

# 绘制水平条形图
plt.figure(figsize=[10, 9])
# 获取barh返回的条形容器对象,这是关键
bars = plt.barh(df.coins, df.dominance)
# 给每个条形添加数值标签,fmt控制显示格式
plt.bar_label(bars, fmt='%.2f')
# 补充图表标题和坐标轴标签,让图表更清晰
plt.title('加密货币市场占比')
plt.xlabel('占比 (%)')
plt.show()

方法二:使用Axes对象(更推荐用于复杂图表)

要是以后你需要做更复杂的图表,用Axes对象会更灵活,写法如下:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({
    "coins": ["BTC", "ETH", "BNB", "XRP", "SOL", "ADA"],
    "dominance": [42.08, 19.38, 3.68, 1.73, 1.55, 1.51]
})
df = df.sort_values(by=["dominance"])

# 创建图表和Axes对象
fig, ax = plt.subplots(figsize=[10, 9])
bars = ax.barh(df.coins, df.dominance)
# 使用Axes的bar_label方法,padding可以调整标签和条形的间距
ax.bar_label(bars, padding=3, fmt='%.2f')
# 设置标题和坐标轴
ax.set_title('加密货币市场占比')
ax.set_xlabel('占比 (%)')
plt.show()

实用小技巧

  • 想给标签加上百分号?把fmt改成fmt='%.2f %%'就行
  • padding参数可以调整标签和条形的距离,避免两者挤在一起
  • 要是想让标签显示在条形内部,加上label_type='center'参数就可以实现

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 20:32:41