seaborn.catplot 组织函数返回一个 FacetGrid,它使您可以访问无花果、斧头及其补丁。如果在没有绘制任何其他内容的情况下添加标签,您就会知道哪些条形图来自哪些变量。从@LordZsolt 的回答中,我选择了order 的catplot 参数:我喜欢明确说明,因为现在我们不再使用我们认为默认的顺序来依赖barplot 函数。
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 上下文中获得很多样式。试试看——)