python – 使用DataFrame.plot显示堆积条形图中的总计和百分比
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 使用DataFrame.plot显示堆积条形图中的总计和百分比,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1949字,纯文字阅读大概需要3分钟。
内容图文
![python – 使用DataFrame.plot显示堆积条形图中的总计和百分比](/upload/InfoBanner/zyjiaocheng/696/46259eaaa410458dac8188ef1c094201.jpg)
我的数据框如下所示:
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
使用下面的代码,它给出了一个堆积条形图:
df = df.iloc[:, 0:4]
df.plot(x='Airport', kind='barh', stacked=True, title='Breakdown of Costs', mark_right=True)
如何在每个堆积条形图上添加总计(相隔数千1,000)?如何为堆积条形图中的每个段添加%?
解决方法:
您可以使用plt.text根据数据将信息放在位置.
但是,如果你有非常小的条形,可能需要一些调整才能看起来很完美.
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')
编辑:一些任意想法,以提高可读性:
将总值向右移动,使用45°旋转文本:
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)
在顶部和底部对齐的文本之间切换:
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%或更多的条形:
if pc >= 10:
plt.text(cs - ab/2, i, str(np.round(pc, 1)) + '%', va='center', ha='center')
…或仍然打印它们,但垂直:
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)
内容总结
以上是互联网集市为您收集整理的python – 使用DataFrame.plot显示堆积条形图中的总计和百分比全部内容,希望文章能够帮你解决python – 使用DataFrame.plot显示堆积条形图中的总计和百分比所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。