如何在python条形图中的堆叠条形图上添加比例标签 [英] how to add proportion label on the stacked bar chart in python bar chart

查看:153
本文介绍了如何在python条形图中的堆叠条形图上添加比例标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经绘制了堆积的条形图,并且想要在条形图上添加指示其比例的文本,但是不知道如何添加这些标签.

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.

我的代码是

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看起来像(它是数据透视表,所以它具有多个索引)

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.

推荐答案

我认为您想要这样的东西:

I think you want something like this:

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

输出

这篇关于如何在python条形图中的堆叠条形图上添加比例标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆