A waterfall chart is a type of chart created by McKinsey consultants because it looks like a waterfall flow and is called a waterfall chart (WaterfallPlot ). This type of chart combines absolute values with relative values, and is suitable for expressing the quantitative variation relationship between multiple specific values. This article briefly introduces how to use Python to draw this graph. A Waterfall chart is a type of chart created by McKinsey consultants because it looks like a Waterfall flow and is called a Waterfall chart (Waterfall Plot ). This type of chart combines absolute values with relative values, and is suitable for expressing the quantitative variation relationship between multiple specific values. This article briefly introduces how to use Python to draw this graph.
The command is as follows:
1) import the package import numpy as npimport pandas pdimport matplotlib. pyplot as pltfrom matplotlib. ticker import FuncFormatter2) import and clear data def money (x, pos): return "$ {:,. 0f }". format (x) formatter = FuncFormatter (money) index = ['sales', 'returs', '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 (). amounttrans. loc ["net"] = totalblank. loc ["net"] = totalstep = blank. reset_index (drop = True ). repeat (3 ). shift (-1) step [1: 3] = np. nanblank. loc ["net"] = 03) plot the image 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/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 ['amount']> 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 = 'tid ')
Output:
The above is the content of the "Python tutorial" to draw a waterfall chart. For more information, see The PHP Chinese website (www.php1.cn )!