how to plot pareto chart in python

Solutions on MaxInterview for how to plot pareto chart in python by the best coders in the world

showing results for - "how to plot pareto chart in python"
Barry
25 Apr 2018
1def pareto_plot(df, x=None, y=None, title=None, show_pct_y=False, pct_format='{0:.0%}'):
2    xlabel = x
3    ylabel = y
4    tmp = df.sort_values(y, ascending=False)
5    x = tmp[x].values
6    y = tmp[y].values
7    weights = y / y.sum()
8    cumsum = weights.cumsum()
9    
10    fig, ax1 = plt.subplots()
11    ax1.bar(x, y)
12    ax1.set_xlabel(xlabel)
13    ax1.set_ylabel(ylabel)
14
15    ax2 = ax1.twinx()
16    ax2.plot(x, cumsum, '-ro', alpha=0.5)
17    ax2.set_ylabel('', color='r')
18    ax2.tick_params('y', colors='r')
19    
20    vals = ax2.get_yticks()
21    ax2.set_yticklabels(['{:,.2%}'.format(x) for x in vals])
22
23    # hide y-labels on right side
24    if not show_pct_y:
25        ax2.set_yticks([])
26    
27    formatted_weights = [pct_format.format(x) for x in cumsum]
28    for i, txt in enumerate(formatted_weights):
29        ax2.annotate(txt, (x[i], cumsum[i]), fontweight='heavy')    
30    
31    if title:
32        plt.title(title)
33    
34    plt.tight_layout()
35    plt.show()
36
similar questions
queries leading to this page
how to plot pareto chart in python