python - 跳过 seaborn facetgrid 中的空面以​​进行注释

标签 python plot facet seaborn

我正在努力组装一个 Seaborn facetgrid具有使某些网格为空的数据。此外,我用一些统计数据对每个方面进行注释,但我不确定如何“跳过”空方面,以便注释落在正确的方面。

g.axes.flat 长度为 9(9 个面有数据);然而,当我在 g.axes.flat 中的每个元素上放置注释时,它并没有被放置在我期望的位置。

g = sns.FacetGrid(mapping, col=options.facetCol, row=options.facetRow, col_order=sorted(cols), hue=options.group, sharex=False)
g = g.map(sns.distplot, options.axis)

# label each facet with stats
grouped = mapping.groupby([options.facetRow, options.facetCol])
for ax, (name, df) in zip(g.axes.flat, grouped):
    df2 = df.groupby(options.group) # group by each thing that has its own color and run stats on it

    for i, (group, data) in enumerate(df2):
        x = data[options.axis]

        # calculate stats and create label
        n = len(x)
        mean = np.mean(x)
        std = np.std(x)
        label = r"%s: n=%s, $\mu$=%.2f $\sigma$=%.2f" %(group, n, mean, std)
        ax.annotate(label, xy=(0.05,0.9-(i*0.05)), xycoords='axes fraction', ha='left', size=8)

enter image description here

编辑

我已经创建了一个注解函数,并将其传递给 map() [按照推荐];但是我不确定如何将标签名称传递给函数以及如何获取注释(每个方面有两个)在 y 方向上移动。还有更多建议吗?

g = g.map(stats, options.axis)

def stats(x, **kwargs):
    ax = sns.distplot(x, **kwargs)

    # calculate stats and create label
    n = len(x)
    mean = np.mean(x)
    std = np.std(x)
    label = r"%s: n=%s, $\mu$=%.2f $\sigma$=%.2f" %('moo', n, mean, std) # temporary label, need to pass it through function
    i = 1 # temporary, needs to increment to shift annotations so they aren't on top of each other

    # create annotation
    ax.annotate(label, xy=(0.05,0.9-(i*0.05)), xycoords='axes fraction', ha='left', size=8)

enter image description here

最佳答案

最终的解决方案是:

g = sns.FacetGrid(mapping, col=options.facetCol, row=options.facetRow, col_order=sorted(cols), hue=options.group, sharex=False)
g.map(sns.distplot, options.axis)
g.map(stats, options.axis)

# custom function that allows us to create a distplot and add offset annotations to each facet that is not empty
def stats(x, label, **kwargs):

    # get a reference to the currently active axes
    ax = plt.gca()    

    # calculate stats and create label
    n = len(x)
    mean = np.mean(x)
    std = np.std(x)
    label = r"%s: n=%s, $\mu$=%.2f $\sigma$=%.2f" %(label, n, mean, std)

    # create annotation
    y = 0.9 - len(ax.texts) * 0.05
    ax.annotate(label, xy=(0.05,y), xycoords='axes fraction', ha='left', size=8)

关于python - 跳过 seaborn facetgrid 中的空面以​​进行注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31171964/

相关文章:

python - **凹**非网格数据的matplotlib轮廓/轮廓

python - 在 SymPy 中绘制带有复变量的隐式方程

java - Facet 字段值使用字谜多次返回相同的值

r - R 中的分面或分组相关和相关图

python - 如何在Python中求解包含指数的方程?

python - 谷歌应用服务器 "unable to add testProject to attribute application"正则表达式问题中的 yaml 异常?

python - 对一列中位于其他列值和条件语句之间的值进行分组

使用字典和函数的 Python 代码

r - 如何抑制代码但在 R markdown 中显示图?

elasticsearch - 将 ElasticSearch Facets 查询转换为 PyES