how to add proportion label on the stacked bar chart in python bar chart

馋奶兔 提交于 2019-12-25 03:08:01

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/49951472/how-to-add-proportion-label-on-the-stacked-bar-chart-in-python-bar-chart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!