Skip to content

Instantly share code, notes, and snippets.

@egemenzeytinci
Last active September 25, 2021 16:17
Show Gist options
  • Save egemenzeytinci/1ef2564ca394ab2fbec5918f1e0fb41c to your computer and use it in GitHub Desktop.
Save egemenzeytinci/1ef2564ca394ab2fbec5918f1e0fb41c to your computer and use it in GitHub Desktop.
Matplotlib pie chart by n values or threshold
import matplotlib.pyplot as plt
import pandas as pd
def pie_by_first_n(df, label_col, size_col, other_name='others', n=5):
df_sum = df.groupby(label_col)[size_col].sum().reset_index()
df_sum = df_sum.sort_values(by=size_col, ascending=False)
df2 = df_sum[:n].copy()
data = {
label_col: [other_name],
size_col: [df_sum[size_col][n:].sum()],
}
new_row = pd.DataFrame(data)
df2 = pd.concat([df2, new_row])
sizes = df2[size_col]
labels = df2[label_col]
plt.figure(figsize=(15, 10))
plt.pie(sizes, labels=labels, autopct='%1.1f%%', shadow=True, startangle=140, rotatelabels=90)
plt.show()
def pie_by_threshold(df, label_col, size_col, other_name='others', threshold=5.0):
df_sum = df.groupby(label_col).agg({size_col: 'sum'}).apply(lambda x: 100 * x / float(x.sum()))
df_sum = df_sum.reset_index()
df1 = df_sum[df_sum[size_col] >= threshold].copy()
df2 = df_sum[df_sum[size_col] < threshold].copy()
data = {
label_col: [other_name],
size_col: [df2[size_col].sum()],
}
new_row = pd.DataFrame(data)
df_last = pd.concat([df1, new_row])
sizes = df_last[size_col]
labels = df_last[label_col]
plt.figure(figsize=(15, 10))
plt.pie(sizes, labels=labels, autopct='%1.1f%%', shadow=True, startangle=140, rotatelabels=90)
plt.show()
@atcherkasov
Copy link

Thats great!
I found it very useful for my task. My product manager will be happy about new charts)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment