首页 > 解决方案 > 为 seaborn 的 factorplot boxplot 中的每个框添加标签

问题描述

我知道有类似的答案,例如this one,但该答案适用于seaborn的箱线图,并且不适用于seaborn的因子图。在一个简单的因子图上:

import seaborn as sns

tips = sns.load_dataset("tips")

means = tips.groupby(["sex","smoker","time"])["tip"].mean().values
means_labels = [str(int(s)) for s in means]

with sns.plotting_context("notebook",font_scale=2):
    g = sns.factorplot(x="sex", y="total_bill", hue="smoker",\
                   col="time",  data=tips, kind="box", size=6, aspect=.7)

如何在每个框下方添加注释(在上面的示例中为mean_labels),如下所示:

在此处输入图像描述

正如我所说,我尝试使用上面的答案至少尝试获取每个框的位置:

import matplotlib.pyplot as plt
ax = plt.gca()
pos = range(len(means))
for tick,label in zip(pos,ax.get_xticklabels()):
        ax.text(pos[tick], means[tick] + 0.5, meanslabels[tick], 
               horizontalalignment='center', color='r', weight='semibold')

但这会产生:

在此处输入图像描述

我相信这是因为我传递了整个情节的轴而不是“因子图”轴。但是我找不到这样做的方法(如果我使用ax=plt.gca()代替,例如示例中的ax=sns.factorplot(...),则会收到错误消息:AttributeError: module ' seaborn' 没有属性 'gca')。

标签: python-3.xseaborn

解决方案


推荐阅读