【问题标题】:Get sample size for boxplots in seaborn factorplot获取 seaborn factorplot 中箱线图的样本大小
【发布时间】:2018-04-19 20:51:38
【问题描述】:

我希望让样本编号出现在每个箱线图上,如下所示: https://python-graph-gallery.com/38-show-number-of-observation-on-boxplot/

如上面的链接所示,我可以获得列表中的中位数和计数。 但是,我有一个带有色调的因子图,这样 x 刻度的位置似乎没有在 x 轴上被捕获。

使用 seaborn Tips 数据集,我有以下内容:

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

sns.set_style("whitegrid")
tips = sns.load_dataset("tips")

g = sns.factorplot(x="sex", y="total_bill",hue="smoker", 
col="time",data=tips, kind="box",size=4, aspect=.7)

# Calculate number of obs per group & median to position labels
medians = tips.groupby(['time','sex','smoker'])['total_bill'].median().values
nobs =  tips.groupby(['time','sex','smoker']).size()
nobs = [str(x) for x in nobs.tolist()]
nobs = ["n: " + i for i in nobs]


plt.show()

Here is the plot

我想得到“n:[观察次数]”就在中位数之上,我想知道是否有办法得到那个 x-tick。此外,假设某些组并不总是同时具有男性和女性,因此它不能只是硬编码。

【问题讨论】:

    标签: python seaborn boxplot


    【解决方案1】:

    这里发生了几件棘手的事情:

    1. 您有两个子轴,一个用于每个主图。你需要遍历这些。

    2. 每个轴上有多个 x 偏移箱线图。您需要考虑到这一点。

    3. 一旦你知道你在哪里绘制,你需要知道哪个图在那里被可视化,因为排序(先是“是”还是先“否”?先是“男性”还是“女性”?) '不保证。

    幸运的是,如果您将数据框编入索引(或在本例中为多索引),您只需要时间、性别和吸烟的文本即可获得正确的值。这些都可以通过一点挖掘获得。生成的代码如下所示(注意对mediansnobs 的更改):

    medians = tips.groupby(['time','sex','smoker'])['total_bill'].median()
    nobs =  tips.groupby(['time','sex','smoker']).apply(lambda x: 'n: {}'.format(len(x)))
    
    for ax in plt.gcf().axes:
        ax_time = ax.get_title().partition(' = ')[-1]
    
        for tick, label in enumerate(ax.get_xticklabels()):
            ax_sex = label.get_text()
    
            for j, ax_smoker in enumerate(ax.get_legend_handles_labels()[1]):
                x_offset = (j - 0.5) * 2/5
                med_val = medians[ax_time, ax_sex, ax_smoker]
                num = nobs[ax_time, ax_sex, ax_smoker]
    
                ax.text(tick + x_offset, med_val + 0.1, num,
                        horizontalalignment='center', size='x-small', color='w', weight='semibold')
    

    为了验证,这里是nobs 系列:

    time    sex     smoker
    Lunch   Male    Yes       n: 13
                    No        n: 20
            Female  Yes       n: 10
                    No        n: 25
    Dinner  Male    Yes       n: 47
                    No        n: 77
            Female  Yes       n: 23
                    No        n: 29
    

    【讨论】:

    • 偏移量中的 .5 和 2/5 是如何得出的?
    • 刻度之间的距离似乎是 2.5 * 箱线图的宽度,或 5 * 半箱线图的宽度。因此,1/5+-0.2 将偏离刻度线的中心,正好是箱线图的一半,因此位于中心。 0.5 是将j 将采用的值[0, 1] 转换为两个关于刻度线对称的值[-0.5, 0.5]。因此,+-0.5 * 2/5 = +-0.2.
    • 我认为对于距离更通用,你可以这样做:x_offset = (j - (num_labels-1)/2) * (num_labels/((num_labels*num_sex)+num_sex-1 ))
    • 如果我没有“时间”变量,只有两组,我该怎么办?
    猜你喜欢
    • 2014-11-27
    • 2019-09-14
    • 1970-01-01
    • 2016-01-25
    • 2018-08-05
    • 1970-01-01
    • 2018-01-15
    • 2021-06-14
    相关资源
    最近更新 更多