简体   繁体   English

如何 plot 使用 matplotlib 或 ZD50F43649ZD63 的 2 个分类列的 plot 条

[英]How to plot a bar plot of 2 categorical columns using matplotlib or seaborn

This might be a simple task but I am new to plotting in python and is struggling to convert logic into code.这可能是一项简单的任务,但我是在 python 中绘图的新手,并且正在努力将逻辑转换为代码。 I have 2 columns like below.我有 2 列,如下所示。 0 mean not churned and 1 means churned. 0 表示未流失,1 表示已流失。 gender is an object column and churned is a category column性别是 object 列,流失是类别列

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).我只想要一个堆叠条形图(如果这不是正确的图表选择,请纠正我)在 x 轴(流失列)上具有 0 和 1,对于这两个类别中的每一个,我想要一个具有 2 种不同颜色的堆叠条形图每个性别显示 0 岁以下的男性和女性总数(未流失)和 1 岁以下的男性和女性总数(流失)。

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.它给了我每个 0 和 1 的总数,但我也需要将它除以性别。

Hope I am making sense希望我说得通

You can table it:您可以将其表:

import pandas as pd
df = pd.DataFrame({'gender':['male','male','female','female','female','male'],
                'churned':[0,1,0,1,1,1]})
pd.crosstab(df['churned'],df['gender']).plot(kind="bar",stacked=True)

在此处输入图像描述

If you wanted an interactive version then you could use hvplot:如果你想要一个交互式版本,那么你可以使用 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]: 

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM