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

如何用pandas/seaborn/matplotlib将barh图条形标签右对齐?

如何将水平条形图(barh)的条形标签对齐到条形右侧

当前我使用以下代码生成水平条形图,希望把条形标签(比如John、Amy这些)对齐到条形的右侧:

import pandas as pd
import seaborn as sns
sns.set_style('white')


s = pd.Series({'John': 7, 'Amy': 4, 'Elizabeth': 4, 'James': 4, 'Roy': 2})
color1 = ['orange', 'grey', 'grey','grey','grey']

ax1 = s.plot(kind='barh', color=color1, figsize=(6, 3), width=.8)
ax1.invert_yaxis()
ax1.bar_label(ax1.containers[0], labels=s.index, padding=-60, color='white',
             fontsize=12, fontweight='bold')
ax1.bar_label(ax1.containers[0], padding=10, color='black',
             fontsize=8, fmt='{:.0f} times'.format, fontweight='bold')
ax1.set_xticks([])
ax1.set_yticks([])
sns.despine(bottom=True, left=True)

生成的图表如下:
当前生成的水平条形图

请告诉我如何通过pandas、seaborn或matplotlib实现标签对齐到条形右侧的效果。


解决方案:利用matplotlib的水平对齐参数实现

直接在bar_label方法中添加ha='right'(horizontalalignment='right'的简写)参数,即可让标签对齐到条形的右侧边缘,再配合调整padding值控制标签与条形的间距。

修改后的完整代码:

import pandas as pd
import seaborn as sns
sns.set_style('white')


s = pd.Series({'John': 7, 'Amy': 4, 'Elizabeth': 4, 'James': 4, 'Roy': 2})
color1 = ['orange', 'grey', 'grey','grey','grey']

ax1 = s.plot(kind='barh', color=color1, figsize=(6, 3), width=.8)
ax1.invert_yaxis()
# 核心修改:添加ha='right',并调整padding为-10(可根据需求微调)
ax1.bar_label(ax1.containers[0], labels=s.index, padding=-10, color='white',
             fontsize=12, fontweight='bold', ha='right')
ax1.bar_label(ax1.containers[0], padding=10, color='black',
             fontsize=8, fmt='{:.0f} times'.format, fontweight='bold')
ax1.set_xticks([])
ax1.set_yticks([])
sns.despine(bottom=True, left=True)

关键说明:

  • ha='right':将标签的水平对齐方式设为右对齐,标签的右侧边缘会与条形的右侧边缘对齐。
  • padding参数:负数代表标签向条形内部偏移,正数则向外偏移。可根据条形宽度、字体大小微调数值(比如-8到-15之间),让标签贴合条形右侧的效果更自然。
  • 该方法完全兼容pandas、seaborn的绘图逻辑,因为pandas的plot底层依赖matplotlib实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 07:00:22