The waterfall chart is a type of chart created by McKinsey's consulting firm, which is known as the waterfall (Waterfall plot), which resembles waterfall water. This type of chart uses absolute and relative values in a way that is useful for expressing the number-change relationship between multiple specific values. This article briefly describes how to draw the diagram using Python.
The command is as follows
1) Import Package imports NumPy as Npimport pandas as Pdimport Matplotlib.pyplot as Pltfrom matplotlib.ticker import FuncFormatter2) and clean Data def money (x, POS): Return "${:,.0f}". Format (x) formatter = Funcformatter (money) index = [' Sales ', ' returns ', ' credits 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 (). amounttrans.loc["NET"]= totalblank.loc["net"] = Totalstep = Blank.reset_index (drop=true). Repeat (3). Shift ( -1) Step[1: : 3] = np.nanblank.loc["NET"] = 03) Draw Image My_plot = Trans.plot (kind= ' bar ', Stacked=true, Bottom=blank,legend=none, figsize= (5), title= "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/25pos_offset = max/50plot_offset = Int (MAX/15) loop = 0for Index, row in Trans.iterrows (): If row[' amount '] = = Total:y = Y_height[loop]else:y = Y_height[loop] + row[' amount ']if row[' Amou NT '] > 0:y + = pos_offsetelse:y-= Neg_offsetmy_plot.annotate ("{:,. 0f}". Format (row[' Amount ']), (loop,y), ha= "center" ) Loop+=1my_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 ')
The output is as follows
The above is the "Python tutorial" to draw the content of the waterfall, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!