总结
豆包 AI 助手文章总结

【Python教程】绘制瀑布图

黄舟
发布: 2017-02-07 16:09:21
原创
3112人浏览过

瀑布图是由麦肯锡顾问公司所独创的图表类型,因为形似瀑布流水而称之为瀑布图( waterfall plot)。此种图表采用绝对值与相对值结合的方式,多适用于表达多个特定数值之间的数量变化关系。本文简单介绍如何利用python绘制该图。

命令如下

1)导入程序包
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
2)导入及清理数据
def money(x, pos):
return "${:,.0f}".format(x)
formatter = FuncFormatter(money)
index = ['sales','returns','credit fees','rebates','late charges','shipping']
data = {'amount': [350000,-30000,-7500,-25000,95000,-7000]}
trans = pd.DataFrame(data=data,index=index)
blank = trans.amount.cumsum().shift(1).fillna(0)
total = trans.sum().amount
trans.loc["net"]= total
blank.loc["net"] = total
step = blank.reset_index(drop=True).repeat(3).shift(-1)
step[1::3] = np.nan
blank.loc["net"] = 0
3)绘制图像
my_plot = trans.plot(kind='bar', stacked=True, bottom=blank,legend=None, figsize=(10, 5), title="2014 Sales Waterfall")
my_plot.plot(step.index, step.values,'k')
my_plot.set_xlabel("Transaction Types")
my_plot.yaxis.set_major_formatter(formatter)
y_height = trans.amount.cumsum().shift(1).fillna(0)
max = trans.max()
neg_offset = max / 25
pos_offset = max / 50
plot_offset = int(max / 15)
loop = 0
for index, row in trans.iterrows():
if row['amount'] == total:
y = y_height[loop]
else:
y = y_height[loop] + row['amount']
if row['amount'] > 0:
y += pos_offset
else:
y -= neg_offset
my_plot.annotate("{:,.0f}".format(row['amount']),(loop,y),ha="center")
loop+=1
my_plot.set_ylim(0,blank.max()+int(plot_offset))
my_plot.set_xticklabels(trans.index,rotation=0)
my_plot.get_figure().savefig("waterfall.png",dpi=200,bbox_inches='tight')
登录后复制

输出如下

977.jpg

以上就是【Python教程】绘制瀑布图的内容,更多相关内容请关注PHP中文网(www.php.cn)!

python速学教程(入门到精通)
python速学教程(入门到精通)

python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
豆包 AI 助手文章总结
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号