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

Place labels on top of each stacked bar, and set font color in matplotlib

I have the following code (DF and graph):

import pandas as pd
import matplotlib.pyplot as plt

data = [['2005','A',10],['2006','A',15],['2007','A',10],
                       ['2005','B',15],['2006','B',70],['2007','B',10],
                       ['2005','C',75],['2006','C',15],['2007','C',80]
                      ]


df = pd.DataFrame(
    data=data, 
    columns=['year','type','count'])

fig, ax = plt.subplots(figsize=(15, 7),facecolor = '#fdf1e6')
ax.set_facecolor('#fdf1e6')

ax = sns.histplot(df, x='year', 
                  hue='type', 
                  weights='count',
                  multiple='stack', 
                  shrink=0.9,
                  linewidth=3.5,
                  )

ax.get_legend().remove()

for c in ax.containers:
    ax.bar_label(c, fmt=lambda x: f'{x:.0%}' if x > 0 else '', label_type='center')

and the result is

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 to place each stack label on top of each stack (now is centered in each stack) and change font color to white.

Any idea?

Thanks!!!

>Solution :

Removing label_type='center' (the default is 'edge'), using a negative value for padding, and the color parameter, something like:

ax.bar_label(c, fmt=lambda x: f'{x:.0%}' if x > 0 else '', color='w', padding=-15)

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