Home > Back-end >  Python Seaborn : Pie chart from count of values (showing the percentage too)
Python Seaborn : Pie chart from count of values (showing the percentage too)

Time:09-06

I have a dataframe like below-

df = pd.DataFrame([
    ['Fully Paid',1,1],
    ['Fully Paid',1,1],
    ['Fully Paid',1,0],
    ['Defaulted',1,0],
    ['Defaulted',1,0]
], columns=['LoanStatus', 'B', 'C'])

I am looking to plot this in a pie chart showing 60% of loan status is fully paid while 40% is defaulted. I am able to do this in a count plot but unable to do it in a pie chart -

COUNT PLOT: 

sns.countplot(x="LoanStatus",data=df)

EXPECTED:

A pie chart showing how many values are there with both the loan status along with the percentage.

CodePudding user response:

You can do this to get the pie plot. Adjust the fmt if you want to show the value and percentage differently.

#df.LoanStatus.
df = pd.DataFrame([
    ['Fully Paid',1,1],
    ['Fully Paid',1,1],
    ['Fully Paid',1,0],
    ['Defaulted',1,0],
    ['Defaulted',1,0]
], columns=['LoanStatus', 'B', 'C'])

total = df['LoanStatus'].value_counts().values.sum()

def fmt(x):
    return '{:.1f}%\n{:.0f}'.format(x, total*x/100)

plt.pie(df['LoanStatus'].value_counts().values, labels=df['LoanStatus'].value_counts().index, autopct=fmt)

enter image description here

Additional info - The def fmt() is a function which will be called for each entry while plotting. The value x will be the input which is the auto percent calculated (3/5100=60 and 2/5100=40). There are some more examples of using this enter image description here

  • Related