Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

apply different formatting to only one bar label in matplotlib's bar label

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)

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading