首页 > 解决方案 > 使用不同的色调分组覆盖对 seaborn 的 FacetGrid 的多个调用

问题描述

使用 seaborn 的 FacetGrid,我想在多个映射调用之间更新“色调”分组参数。具体来说,我最初有一个自定义绘图函数,它采用“色调”分组,在此之上我想显示组的平均值(因此忽略色调并汇总所有数据)。

例如

g = sns.FacetGrid(tips, col="time",  hue="smoker")
g = (g.map(plt.scatter, "total_bill", "tip", edgecolor="w").add_legend())
g = (g.map(sns.regplot, "total_bill", "tip").add_legend())

将为每个组创建一条彩色回归线。如何更新 FacetGrid 以忽略hue第二次调用时的分组map?在此示例中,我希望有两个彩色散点图,其中覆盖了一条(黑色)回归线。

标签: pythonseaborn

解决方案


色调用于FacetGrid对输入数据进行分组。它不能只对它进行部分分组。

matplotlib 解决方案可能看起来像

import matplotlib.pyplot as plt
import seaborn as sns

tips = sns.load_dataset("tips", cache=True)

n = len(tips["time"].unique())
usmoker = tips["smoker"].unique()

fig, axes = plt.subplots(ncols=n, sharex=True, sharey=True)

for ax, (time, grp1) in zip(axes.flat, tips.groupby("time")):
    ax.set_title(time)
    ax.set_prop_cycle(plt.rcParams["axes.prop_cycle"])

    for smoker in usmoker:
        grp2 = grp1[grp1["smoker"] == smoker]
        sns.regplot("total_bill", "tip", data=grp2, label=str(smoker), 
                    fit_reg=False, ax=ax)
    ax.legend(title="Smoker")  

for ax, (time, grp1) in zip(axes.flat, tips.groupby("time")):
    sns.regplot("total_bill", "tip", data=grp1, ax=ax, scatter=False, 
                color="k", label="regression line")


plt.show()

在此处输入图像描述


推荐阅读