0

I have plotted stacked bar chart and want to add text indicating its proportion on the bar but do not know how I can add those labels on.

My codes are,

tps = df3[df3['Action Type_new']!='NA'].pivot_table(values=['Column'], 
                  index='year',
                  columns='Action Type_new',
                  aggfunc='sum')

tps = tps.div(tps.sum(1), axis=0)
tps.plot(kind='bar', stacked=True)

and my tps looks like, (it is pivot table so, it has multi index)

MultiIndex(levels=[['Column'], ['Less Severe', 'Severe']],
           labels=[[0, 0], [0, 1]],
           names=[None, 'Action Type_new'])


Column
Action Type_new Less Severe Severe
year        
1990    0.208409    0.791591
1991    0.276577    0.723423
1992    0.281479    0.718521    
1993    0.402501    0.597499
1994    0.430871    0.569129
1995    0.445519    0.554481
1996    0.509341    0.490659
1997    0.604371    0.395629
1998    0.716450    0.283550
1999    0.578597    0.421403

My current bar chart is like below.

enter image description here

MMM
  • 425
  • 1
  • 7
  • 24

1 Answers1

2

Update using matplotlib 3.4.2

Thanks @TentonMcKinney

df1 = df['Column']
ax = df1.plot(kind='bar',stacked=True)
for c in ax.containers[::2]:
    ax.bar_label(c, label_type='edge', fmt='%0.1f', padding=10)
ax.legend(loc='lower right')

Output:

enter image description here


I think you want something like this:

Where df:

                     Column          
Action Type_new Less Severe    Severe
Year                                 
1990               0.208409  0.791591
1991               0.276577  0.723423
1992               0.281479  0.718521
1993               0.402501  0.597499
1994               0.430871  0.569129
1995               0.445519  0.554481
1996               0.509341  0.490659
1997               0.604371  0.395629
1998               0.716450  0.283550
1999               0.578597  0.421403

import matplotlib.pyplot as plt

df1 = df['Column']
ax = df1.plot(kind='bar',stacked=True)
for rec, label in zip(ax.patches,df1['Less Severe'].round(1).astype(str)):
    height = rec.get_height()
    ax.text(rec.get_x() + rec.get_width() / 2, height + .05, label,
           ha = 'center', va='bottom')
plt.legend(loc='lower right')

Output

enter image description here

Scott Boston
  • 147,308
  • 15
  • 139
  • 187
  • 1
    How can I utilize this code chunk to produce the text labels for every feature? (Less Severe AND Severe)… The problem is that if I nest this loop over the range of all features, then the text label gets printed in the same location for all the features – Bharat Desai Jan 07 '20 at 05:52
  • 1
    The answer to the question in my comment above was utilizing the logic to add labels found in the following thread instead: https://stackoverflow.com/questions/39279404/adding-labels-to-stacked-bar-chart – Bharat Desai Jan 07 '20 at 06:32