I want to apply different formatting to only 1 bar label in matplotlib’s bar labels.
Example Code
import pandas as pd
import seaborn as sns
sns.set_style('white')
s = pd.Series({'John': 10000, 'Amy': 5000, 'Elizabeth': 2000, 'James': 3000, 'Roy': 4000})
color1 = ['orange', 'lightgrey', 'lightgrey','lightgrey','lightgrey']
ax1 = s.plot(kind='barh', color=color1, figsize=(6, 3), width=.8)
labels = ax1.bar_label(ax1.containers[0], padding=-10, color='black', fontsize=10)
for label in labels:
label.set_ha('right')
ax1.set_xticks([])
sns.despine(bottom=True, left=True)
I want change John’s bar label to size 20, bold, white color.
also want to utilize s.index to target John.
Which code should I use?
Thank you for all your help!
>Solution :
You could change your loop to detect the value to change:
labels = ax1.bar_label(ax1.containers[0], padding=-10, color='black', fontsize=10)
for label in labels:
label.set_ha('right')
if label.get_text() == '10000':
label.set_color('w')
label.set_fontweight('bold')
label.set_fontsize(20)
Or by position/label:
i = s.index.get_loc('John') # 0
labels[i].set_color('w')
labels[i].set_fontweight('bold')
labels[i].set_fontsize(20)
Output:

