python barplot宽度_python – 频率和百分比不均匀组sns barplot

我试图在sns条形图中按组显示相对百分比以及总频率.我比较的两个组的大小差别很大,这就是我在下面的函数中按组显示百分比的原因.

以下是我创建的示例数据框的语法,该数据框与目标分类变量(‘item’)中的数据(‘groups’)具有相似的相对组大小. ‘rand’只是我用来制作df的变量.

# import pandas and seaborn

import pandas as pd

import seaborn as sns

import numpy as np

# create dataframe

foobar = pd.DataFrame(np.random.randn(100, 3), columns=('groups', 'item', 'rand'))

# get relative groupsizes

for row, val in enumerate(foobar.rand) :

if val > -1.2 :

foobar.loc[row, 'groups'] = 'A'

else:

foobar.loc[row, 'groups'] = 'B'

# assign categories that I am comparing graphically

if row < 20:

foobar.loc[row, 'item'] = 'Z'

elif row < 40:

foobar.loc[row, 'item'] = 'Y'

elif row < 60:

foobar.loc[row, 'item'] = 'X'

elif row < 80:

foobar.loc[row, 'item'] = 'W'

else:

foobar.loc[row, 'item'] = 'V'

这是我写的函数,它按组比较相对频率.它有一些默认变量,但我已经为这个问题重新分配了它们.

def percent_categorical(item, df=IA, grouper='Active Status') :

# plot categorical responses to an item ('column name')

# by percent by group ('diff column name w categorical data')

# select a data frame (default is IA)

# 'Active Status' is default grouper

# create df of item grouped by status

grouped = (df.groupby(grouper)[item]

# convert to percentage by group rather than total count

.value_counts(normalize=True)

# rename column

.rename('percentage')

# multiple by 100 for easier interpretation

.mul(100)

# change order from value to name

.reset_index()

.sort_values(item))

# create plot

PercPlot = sns.barplot(x=item,

y='percentage',

hue=grouper,

data=grouped,

palette='RdBu'

).set_xticklabels(

labels = grouped[item

].value_counts().index.tolist(), rotation=90)

#show plot

return PercPlot

功能和结果图如下:

percent_categorical('item', df=foobar, grouper='groups')

这很好,因为它允许我按组显示相对百分比.但是,我还想显示每个组的绝对数字,最好是在图例中.在这种情况下,我希望它表明A组共有89名成员,B组有11名成员.

预先感谢您的任何帮助.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值