使用DataFrame.plot在堆叠的条形图中显示总计和百分比 [英] Display totals and percentage in stacked bar chart using DataFrame.plot

查看:1134
本文介绍了使用DataFrame.plot在堆叠的条形图中显示总计和百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据框如下所示:

  Airport  ATA Cost  Destination Handling  Custom  Total Cost
0     PRG    599222                 11095   20174      630491
1     LXU    364715                 11598   11595      387908
2     AMS    401382                 23562   16680      441623
3     PRG    599222                 11095   20174      630491 

使用以下代码可以显示堆积的条形图:

Using below codes it gives a stacked bar chart:

df = df.iloc[:, 0:4]    
df.plot(x='Airport', kind='barh', stacked=True, title='Breakdown of Costs', mark_right=True)    

如何在每个堆叠的条形图上添加总计(以千为单位,以千为单位)?如何为堆积的条形图中的每个细分添加%?

How to add the totals (separated by thousands 1,000) over each stacked bar chart? How to add % for each segments in the stacked bar chart?

推荐答案

您可以使用plt.text根据信息将信息放置在各个位置.

You can use plt.text to place the information at the positions according to your data.

但是,如果条形很小,则可能需要进行一些调整才能看起来完美.

However, if you have very small bars, it might need some tweaking to look perfect.

df_total = df['Total Cost']
df = df.iloc[:, 0:4]
df.plot(x = 'Airport', kind='barh',stacked = True, title = 'Breakdown of Costs', mark_right = True)

df_rel = df[df.columns[1:]].div(df_total, 0)*100

for n in df_rel:
    for i, (cs, ab, pc, tot) in enumerate(zip(df.iloc[:, 1:].cumsum(1)[n], df[n], df_rel[n], df_total)):
        plt.text(tot, i, str(tot), va='center')
        plt.text(cs - ab/2, i, str(np.round(pc, 1)) + '%', va='center', ha='center')

一些更好的可读性的想法:

Some arbitrary ideas for better readability:

将总值向右移动,使用45°旋转文字:

shift the total values to the right, use 45° rotated text:

    plt.text(tot+10000, i, str(tot), va='center')
    plt.text(cs - ab/2, i, str(np.round(pc, 1)) + '%', va='center', ha='center', rotation=45)

在顶部和底部对齐的文本之间切换:

switch between top- and bottom-aligned text:

va = ['top', 'bottom']
va_idx = 0
for n in df_rel:
    va_idx = 1 - va_idx
    for i, (cs, ab, pc, tot) in enumerate(zip(df.iloc[:, 1:].cumsum(1)[n], df[n], df_rel[n], df_total)):
        plt.text(tot+10000, i, str(tot), va='center')
        plt.text(cs - ab/2, i, str(np.round(pc, 1)) + '%', va=va[va_idx], ha='center')

仅标记10%或以上的条形:

label only bars with 10% or more:

if pc >= 10:
    plt.text(cs - ab/2, i, str(np.round(pc, 1)) + '%', va='center', ha='center')

...或仍然打印它们,但垂直:

...or still print them, but vertical:

if pc >= 10:
    plt.text(cs - ab/2, i, str(np.round(pc, 1)) + '%', va='center', ha='center')
else:
    plt.text(cs - ab/2, i, str(np.round(pc, 1)) + '%', va='center', ha='center', rotation=90)

这篇关于使用DataFrame.plot在堆叠的条形图中显示总计和百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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