Home > OS >  Stacked bars are unexpectedly annotated with the sum of bar heights
Stacked bars are unexpectedly annotated with the sum of bar heights

Time:12-09

My data:

names_col = ['Count','Freq']
dat = [['Matching', 56935],['Mismatching', 100587]]
plot_df = pd.DataFrame(data=dat,columns=names_col)

I trying plot stacked catplot with showing values , there is my code:

plt.figure(figsize=(16,9))
p=plot_df.set_index('Count').T.plot(kind='bar', stacked=True)
p.bar_label(p.containers[0])
p.bar_label(p.containers[1])
plt.show();

First of all, output of figure not in size (16,9), what wrong? And the second plot show value as: enter image description here

instead value for matching - 56935 (here its ok), and mismatching - 100587, plot show total(157522). How I can access and show also to Mismatching value?

CodePudding user response:

You can set figsize as parameter of plot. Then for each of your containers, add the bar label and your own text:

p=plot_df.set_index('Count').T.plot(kind='bar', stacked=True, figsize=(16,9)) 
for x in p.containers:
    p.bar_label(x)
    p.text(0, x[0].get_y()   x[0].get_height()*0.5, x.datavalues[0], ha='center', color='w', weight='bold')

plt.show()

Output: enter image description here

CodePudding user response:

  • Use enter image description here

    • Here's a more thorough example with multiple groups
      • The other answer does not place the middle annotations for the second group of bars.
    # test data 
    data = {'Matching': [56935, 17610], 'Mismatching': [100587, 13794], 'Test': [33139, 23567]}
    df = pd.DataFrame(data=data, index=['Freq', 'Freq2'])
    
    axe = df.plot(kind='bar', stacked=True, figsize=(16,9), rot=0)
    
    for x in axe.containers:
        axe.bar_label(x, label_type='edge', weight='bold')
        axe.bar_label(x, label_type='center', weight='bold', color='white')
    

    enter image description here

  • Related