Python:在seaborn bar p中绘制百分比

2024-06-26 01:45:11 发布

您现在位置:Python中文网/ 问答频道 /正文

对于数据帧

import pandas as pd
df=pd.DataFrame({'group':list("AADABCBCCCD"),'Values':[1,0,1,0,1,0,0,1,0,1,0]})

我试图绘制一个条形图,显示A, B, C, D取零(或一)次的百分比。

我有一条迂回的路可以走,但我想必须有一条更直的路

tempdf=df.groupby(['group','Values']).Values.count().unstack().fillna(0)
tempdf['total']=df['group'].value_counts()
tempdf['percent']=tempdf[0]/tempdf['total']*100

tempdf.reset_index(inplace=True)
print tempdf

sns.barplot(x='group',y='percent',data=tempdf)

如果它只是绘制平均值,我可以对df数据帧执行sns.barplot,而不是tempdf。如果我对绘制百分比感兴趣的话,我不知道怎样才能做得优雅。

谢谢


Tags: 数据importpandasdfasgroup绘制total
3条回答

您可以将熊猫与seaborn结合使用,以简化此过程:

import pandas as pd
import seaborn as sns

df = sns.load_dataset("tips")
x, y, hue = "day", "proportion", "sex"
hue_order = ["Male", "Female"]

(df[x]
 .groupby(df[hue])
 .value_counts(normalize=True)
 .rename(y)
 .reset_index()
 .pipe((sns.barplot, "data"), x=x, y=y, hue=hue))

enter image description here

您可以在sns.barplotestimator中使用自己的函数,如docs

estimator : callable that maps vector -> scalar, optional
Statistical function to estimate within each categorical bin.

对于您的情况,可以将函数定义为lambda:

sns.barplot(x='group', y='Values', data=df, estimator=lambda x: sum(x==0)*100.0/len(x))

enter image description here

可以使用库Dexplot,它能够返回分类变量的相对频率。它的API与Seaborn类似。将要获取相对频率的列传递给agg参数。如果您想用另一列对其进行细分,请使用hue参数进行细分。以下返回原始计数。

import dexplot as dxp
dxp.aggplot(agg='group', data=df, hue='Values')

enter image description here

要获取相对频率,请将normalize参数设置为要规范化的列。使用'all'在总计数上正常化。

dxp.aggplot(agg='group', data=df, hue='Values', normalize='group')

enter image description here

'Values'列进行规范化将生成以下图表,其中所有“0”条的总数为1。

dxp.aggplot(agg='group', data=df, hue='Values', normalize='Values')

enter image description here

相关问题 更多 >