瀑布圖是由麥肯錫顧問公司所獨創(chuàng)的圖表類型,因為形似瀑布流水而稱之為瀑布圖( waterfall plot)。此種圖表采用絕對值與相對值結(jié)合的方式,多適用于表達(dá)多個特定數(shù)值之間的數(shù)量變化關(guān)系。本文簡單介紹如何利用python繪制該圖。
命令如下
1)導(dǎo)入程序包 import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib.ticker import FuncFormatter 2)導(dǎo)入及清理數(shù)據(jù) 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')
輸出如下
以上就是【Python教程】繪制瀑布圖的內(nèi)容,更多相關(guān)內(nèi)容請關(guān)注PHP中文網(wǎng)(www.miracleart.cn)!
python怎么學(xué)習(xí)?python怎么入門?python在哪學(xué)?python怎么學(xué)才快?不用擔(dān)心,這里為大家提供了python速學(xué)教程(入門到精通),有需要的小伙伴保存下載就能學(xué)習(xí)啦!
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://www.miracleart.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號