如何在Seaborn的酒吧上方增加百分比? [英] How to add percentages on top of bars in seaborn?

查看:260
本文介绍了如何在Seaborn的酒吧上方增加百分比?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于以下计数图,我如何在条形图的顶部放置百分比?

Given the following count plot how do I place percentages on top of the bars?

import seaborn as sns
sns.set(style="darkgrid")
titanic = sns.load_dataset("titanic")
ax = sns.countplot(x="class", hue="who", data=titanic)

例如,对于第一名",我要在其各自的栏顶部总计第一名男性/总第一名,总第一名女性/总第一名和总计第一名孩子/总第一名.

For example for "First" I want total First men/total First, total First women/total First, and total First children/total First on top of their respective bars.

如果我的解释不清楚,请让我知道.

Please let me know if my explanation is not clear.

谢谢!

推荐答案

sns.barplot并不像matplotlib.pyplot.bar那样显式返回小节值(请参阅最后一节),但是如果您未作任何其他绘制,则可以假设轴中的所有patches都是您的值,则可能会有风险.然后,您可以使用barplot函数为您计算的小计:

sns.barplot doesn't explicitly return the barplot values the way matplotlib.pyplot.bar does (see last para), but if you've plotted nothing else you can risk assuming that all the patches in the axes are your values. Then you can use the sub-totals that the barplot function has calculated for you:

from matplotlib.pyplot import show
import seaborn as sns
sns.set(style="darkgrid")
titanic = sns.load_dataset("titanic")
total = float(len(titanic)) # one person per row 
#ax = sns.barplot(x="class", hue="who", data=titanic)
ax = sns.countplot(x="class", hue="who", data=titanic) # for Seaborn version 0.7 and more
for p in ax.patches:
    height = p.get_height()
    ax.text(p.get_x()+p.get_width()/2.,
            height + 3,
            '{:1.2f}'.format(height/total),
            ha="center") 
show()

产生

另一种方法是显式进行子求和,例如使用出色的pandas并使用matplotlib进行绘制,还可以自己进行样式设置. (尽管即使使用matplotlib绘图功能,您也可以从sns上下文中获得很多样式.尝试一下-)

An alternate approach is to do the sub-summing explicitly, e.g. with the excellent pandas, and plot with matplotlib, and also do the styling yourself. (Though you can get quite a lot of styling from sns context even when using matplotlib plotting functions. Try it out -- )

这篇关于如何在Seaborn的酒吧上方增加百分比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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