如何在seaborn的条形顶部添加百分比 [英] How to add percentages on top of bars in seaborn

查看:26
本文介绍了如何在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.

推荐答案

seaborn.catplot 组织函数返回一个 FacetGrid,它使您可以访问无花果、斧头及其补丁.如果在未绘制任何其他内容时添加标签,您就会知道哪些条形补丁来自哪些变​​量.从@LordZsolt 的回答中,我选择了 catplotorder 参数:我喜欢明确说明这一点,因为现在我们不依赖于使用我们认为的顺序的 barplot 函数默认.

The seaborn.catplot organizing function returns a FacetGrid, which gives you access to the fig, the ax, and its patches. If you add the labels when nothing else has been plotted you know which bar-patches came from which variables. From @LordZsolt's answer I picked up the order argument to catplot: I like making that explicit because now we aren't relying on the barplot function using the order we think of as default.

import seaborn as sns
from itertools import product

titanic = sns.load_dataset("titanic")

class_order = ['First','Second','Third'] 
hue_order = ['child', 'man', 'woman']
bar_order = product(class_order, hue_order)

catp = sns.catplot(data=titanic, kind='count', 
                   x='class', hue='who',
                   order = class_order, 
                   hue_order = hue_order )

# As long as we haven't plotted anything else into this axis,
# we know the rectangles in it are our barplot bars
# and we know the order, so we can match up graphic and calculations:

spots = zip(catp.ax.patches, bar_order)
for spot in spots:
    class_total = len(titanic[titanic['class']==spot[1][0]])
    class_who_total = len(titanic[(titanic['class']==spot[1][0]) & 
        (titanic['who']==spot[1][1])])
    height = spot[0].get_height() 
    catp.ax.text(spot[0].get_x(), height+3, '{:1.2f}'.format(class_who_total/class_total))

    #checking the patch order, not for final:
    #catp.ax.text(spot[0].get_x(), -3, spot[1][0][0]+spot[1][1][0])

生产

另一种方法是明确地进行求和,例如使用优秀的 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天全站免登陆