Example Code
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)
How can I align the bar labels on the right side of the bar in the plot?
I am looking for a way to fix this using any of the following libraries: pandas, seaborn, or matplotlib.
Edit:
You can patch Text
manually to change the horizontal alignment and get a better result:
labels = ax1.bar_label(ax1.containers[0], labels=s.index, padding=-5,
color="white", fontsize=12, fontweight="bold")
for label in labels:
label.set_ha('right')
Output:
Old answer:
You can use annotate
to more precisely control what you want or use str.rjust
to get labels of the same width. However, since you are not using a monospaced font, the result is approximate:
zlabels = s.index.str.rjust(s.index.str.len().max())
ax1.bar_label(ax1.containers[0], labels=zlabels, padding=-65, color="white",
fontsize=12, fontweight="bold")
Output: