This might be a simple task but I am new to plotting in python and is struggling to convert logic into code. I have 2 columns like below. 0 mean not churned and 1 means churned. gender is an object column and churned is a category column
gender|churned
--------------
male |0
male |1
female |0
female |1
female |1
male |1
I simply want a stacked bar graph (please correct me if this is not the right choice of graph) with 0 and 1 on x axis (churn column) and for each of those 2 categories I want a stacked bar graph with 2 different colours for each gender showing the total number of males and females under 0 (not churned) and total number of males and females under 1(churned).
I tried:
df.Churn.value_counts().plot(kind='bar')
it gave me the total count for each 0 and 1 but i need it divided by gender aswell.
Hope I am making sense
If you wanted an interactive version then you could use hvplot:
import pandas as pd
import hvplot.pandas #noqa
# 1. CREATE DF:
churn = pd.DataFrame({"gender":["male","male","female","female","female","male"],
"churned":[0,1,0,1,1,1]})
churn
Out[2]:
gender churned
0 male 0
1 male 1
2 female 0
3 female 1
4 female 1
5 male 1
# 2. GROUP THE DATA BY "churned" THEN "gender":
plot_me = churn.groupby(["churned","gender"])[["gender"]].count().rename(columns={"gender":"count"})
plot_me
Out[3]:
count
churned gender
0 female 1
male 1
1 female 2
male 2
# 3. PLOT:
plot_me.hvplot.bar(stacked=True,color=["maroon","teal"],line_width=3,
line_color="black",height=350,width=500)
Out[4]:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.