Python:在海洋条形图中绘制百分比 [英] Python: Plotting percentage in seaborn bar plot

查看:1426
本文介绍了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取零(或一个)的时间百分比.

I am trying to plot a barplot showing percentage of times A, B, C, D takes zero (or one).

我对可行的方法有所了解,但我认为必须有更直接的方法

I have a round about way which works but I am thinking there has to be more straight forward way

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数据帧上而不是tempdf上执行sns.barplot.如果我对绘制百分比感兴趣,我不确定如何优雅地做到这一点.

If it were plotting just the mean value, I could simply do sns.barplot on df dataframe than tempdf. I am not sure how to do it elegantly if I am interested in plotting percentages.

谢谢

推荐答案

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

You could use your own function in sns.barplot estimator, as from docs:

估计器:可调用,用于映射向量->标量,可选
统计函数,用于在每个分类箱中进行估计.

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

对于您而言,您可以将函数定义为lambda:

For you case you could define function as lambda:

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

这篇关于Python:在海洋条形图中绘制百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆