How to make Pareto Chart in python?

孤街浪徒 提交于 2019-12-04 19:30:30

You would probably want to create a new column with the percentage in it and plot one column as bar chart and the other as a line chart in a twin axes.

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter

df = pd.DataFrame({'country': [177.0, 7.0, 4.0, 2.0, 2.0, 1.0, 1.0, 1.0]})
df.index = ['USA', 'Canada', 'Russia', 'UK', 'Belgium', 'Mexico', 'Germany', 'Denmark']
df = df.sort_values(by='country',ascending=False)
df["cumpercentage"] = df["country"].cumsum()/df["country"].sum()*100


fig, ax = plt.subplots()
ax.bar(df.index, df["country"], color="C0")
ax2 = ax.twinx()
ax2.plot(df.index, df["cumpercentage"], color="C1", marker="D", ms=7)
ax2.yaxis.set_major_formatter(PercentFormatter())

ax.tick_params(axis="y", colors="C0")
ax2.tick_params(axis="y", colors="C1")
plt.show()

More generalized version of ImportanceOfBeingErnest's code:

def create_pareto_chart(df, by_variable, quant_variable):
    df.index = by_variable
    df["cumpercentage"] = quant_variable.cumsum()/quant_variable.sum()*100

    fig, ax = plt.subplots()
    ax.bar(df.index, quant_variable, color="C0")
    ax2 = ax.twinx()
    ax2.plot(df.index, df["cumpercentage"], color="C1", marker="D", ms=7)
    ax2.yaxis.set_major_formatter(PercentFormatter())

    ax.tick_params(axis="y", colors="C0")
    ax2.tick_params(axis="y", colors="C1")
    plt.show()

And this one includes Pareto by grouping according to a threshold, too. For example: If you set it to 70, it will group minorities beyond 70 into one group called "Other".

def create_pareto_chart(by_variable, quant_variable, threshold):

total=quant_variable.sum()
df = pd.DataFrame({'by_var':by_variable, 'quant_var':quant_variable})
df["cumpercentage"] = quant_variable.cumsum()/quant_variable.sum()*100
df = df.sort_values(by='quant_var',ascending=False)
df_above_threshold = df[df['cumpercentage'] < threshold]
df=df_above_threshold
df_below_threshold = df[df['cumpercentage'] >= threshold]
sum = total - df['quant_var'].sum()
restbarcumsum = 100 - df_above_threshold['cumpercentage'].max()
rest = pd.Series(['OTHERS', sum, restbarcumsum],index=['by_var','quant_var', 'cumpercentage'])
df = df.append(rest,ignore_index=True)
df.index = df['by_var']
df = df.sort_values(by='cumpercentage',ascending=True)


fig, ax = plt.subplots()
ax.bar(df.index, df["quant_var"], color="C0")
ax2 = ax.twinx()
ax2.plot(df.index, df["cumpercentage"], color="C1", marker="D", ms=7)
ax2.yaxis.set_major_formatter(PercentFormatter())

ax.tick_params(axis="x", colors="C0", labelrotation=70)
ax.tick_params(axis="y", colors="C0")
ax2.tick_params(axis="y", colors="C1")

plt.show()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!