0

I am trying to get the percentage labels on top of the stacked bars, but I can't figure it out.

 fig, ax = plt.subplots(figsize=(24, 8))
    minor_treatment_choice.plot( 
      x = 'surgeon_id',  
      kind = 'bar',  
      stacked = True, ax=ax) 
      
    df_total = (minor_treatment_choice['X'] + minor_treatment_choice['Y'])
    df_rel = minor_treatment_choice[minor_treatment_choice.columns[2:]].div(df_total, 0.)*100.
    
    for n in df_rel: 
        for i, (cs, ab, pc) in enumerate(zip(minor_treatment_choice.iloc[:, 2:].cumsum(1)[n], minor_treatment_choice[n], df_rel[n])): 
            plt.text(cs - ab / 2, i, str(np.round(pc, 1)) + '%',  va = 'center', ha = 'center', fontsize = 10)
    
    plt.xticks(fontsize=15,rotation=30)
    plt.yticks(fontsize=15)
    ax.set_xlabel ('Surgeon IDs',fontsize=15)
    ax.set_ylabel ('Minor Severity Cases',fontsize=15)
    fig.suptitle('Treatments X & Y for Minor Cases',fontsize=20)
    ax.legend(title='Treatments')
    plt.show()

Plot

Can anyone help?

dfahsjdahfsudaf
  • 461
  • 4
  • 11
  • Does this answer your question? [Adding value labels on a matplotlib bar chart](https://stackoverflow.com/questions/28931224/adding-value-labels-on-a-matplotlib-bar-chart) or [Stacked Bar Chart with Centered Labels](https://stackoverflow.com/questions/41296313/stacked-bar-chart-with-centered-labels) – Mr. T Feb 18 '21 at 10:32

1 Answers1

0

Using data from the official website, I created an example of percentage annotation. ax.text(x,y,text) is the basic idea. Looking at the current output, it looks like the x-axis is not taken correctly.

import matplotlib.pyplot as plt
import pandas as pd

speed = [0.1, 17.5, 40, 48, 52, 69, 88]
lifespan = [2, 8, 70, 1.5, 25, 12, 28]
index = ['snail', 'pig', 'elephant', 'rabbit', 'giraffe', 'coyote', 'horse']

df = pd.DataFrame({'speed': speed,'lifespan': lifespan}, index=index)

fig, ax = plt.subplots(figsize=(24, 8))
df.plot.bar(stacked=True, ax=ax)

per = df['speed'] / df['speed'].sum()

for i,p in enumerate(per):
    ax.text(i, df.speed[i], '{:.2}%'.format(p), va='center', ha='center', fontsize=14)

ax.set_xticklabels(df.index, fontsize=15, rotation=30)
plt.setp(ax.get_xticklabels(), fontsize=15)
ax.set_xlabel ('Surgeon IDs', fontsize=15)
ax.set_ylabel ('Minor Severity Cases', fontsize=15)
ax.set_title('Treatments X & Y for Minor Cases', fontsize=20)
ax.legend(title='Treatments')

plt.show()

enter image description here

r-beginners
  • 31,170
  • 3
  • 14
  • 32