如何在python条形图中的堆积条形图上添加比例标签

时间:2018-04-21 01:17:29

标签: python pandas matplotlib pivot bar-chart

我已经绘制了堆积条形图,并希望在条形图上添加指示其比例的文字,但不知道如何添加这些标签。

我的代码是,

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)

和我的tps看起来像,(它是数据透视表,所以它有多索引)

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

我目前的条形图如下所示。

enter image description here

1 个答案:

答案 0 :(得分:1)

我想你想要这样的东西:

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')

输出

enter image description here