Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot pandas groupby values in a graph

I have a csv file which contains Gender and Marriage status along with few more columns like below.

Loan_ID,Gender,Married,Dependents,Education,Self_Employed,ApplicantIncome,CoapplicantIncome,LoanAmount,Loan_Amount_Term,Credit_History,Property_Area,Loan_Status
LP001002,Male,No,0,Graduate,No,5849,0,,360,1,Urban,Y
LP001003,Male,Yes,1,Graduate,No,4583,1508,128,360,1,Rural,N
LP001005,Male,Yes,0,Graduate,Yes,3000,0,66,360,1,Urban,Y
LP001006,Male,Yes,0,Not Graduate,No,2583,2358,120,360,1,Urban,Y
LP001008,Male,No,0,Graduate,No,6000,0,141,360,1,Urban,Y
LP001011,Male,Yes,2,Graduate,Yes,5417,4196,267,360,1,Urban,Y

I want to count no. of married Males and Females and show the same in graph as shown below

Below is the code I am using :

import csv
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

if __name__ == '__main__':
    x=[]
    y=[]
    df = pd.read_csv(
        "/home/train.csv",usecols=[1,2]).dropna(subset=['Gender','Married'])  # Reading the dataset in a dataframe using Pandas
    groups = df.groupby(['Gender','Married'])['Married'].apply(lambda x: x.count())
    print(groups)

After group by I have following result :

Gender  Married
Female  No          80
        Yes         31
Male    No         130
        Yes        357

I want the following chart

enter image description here

like image 931
pythonaddict Avatar asked Jul 25 '17 09:07

pythonaddict


1 Answers

You can use groupby + size and then use Series.plot.bar:

Difference between count and size.

groups = df.groupby(['Gender','Married']).size()
groups.plot.bar()

graph

Another solution is add unstack for reshape or crosstab:

print (df.groupby(['Gender','Married']).size().unstack(fill_value=0))
Married   No  Yes
Gender           
Female    80   31
Male     130  357

df.groupby(['Gender','Married']).size().unstack(fill_value=0).plot.bar()

Or:

pd.crosstab(df['Gender'],df['Married']).plot.bar()

graph

like image 66
jezrael Avatar answered Oct 07 '22 18:10

jezrael