Search code examples
pythonmatplotlibstacked-bar-chart

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

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, adding the color parameter, and using get_height to create the desired labels, something like:

    for c in ax.containers:
        labs = [f'{r.get_height():.0%}' if r.get_height() > 0 else '' for r in c]
        ax.bar_label(c, labs, color='w', padding=-15)
    

    Output: enter image description here