以下适用于 seaborn v0.11:
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
g = sns.catplot(x="sex", y="total_bill", hue="smoker", col="time",
data=tips, kind="box",
palette=["#FFA7A0", "#ABEAC9"],
height=4, aspect=.7);
g.map_dataframe(sns.stripplot, x="sex", y="total_bill",
hue="smoker", palette=["#404040"],
alpha=0.6, dodge=True)
# g.map(sns.stripplot, "sex", "total_bill", "smoker",
# palette=["#404040"], alpha=0.6, dodge=True)
plt.show()
说明:在第一遍中,箱线图是使用sns.catplot() 创建的。该函数返回一个sns.FacetGrid,它为分类参数time 的每个值容纳不同的轴。在第二遍中,这个FacetGrid 被重新用于覆盖散点图(sns.stripplot,或者sns.swarmplot)。以上使用方法map_dataframe(),因为data 是带有命名列的pandas DataFrame。 (或者,也可以使用map()。)设置dodge=True 可确保散点图沿每个hue 类别的类别轴移动。最后,请注意,通过使用kind="box" 调用sns.catplot(),然后在第二步中覆盖散点图,可以隐式规避duplicated legend entries 的问题。
替代(不推荐):也可以先创建FacetGrid对象,然后调用map_dataframe()两次。虽然这适用于本示例,但在其他情况下,必须确保属性映射在各个方面正确同步(请参阅docs 中的警告)。 sns.catplot() 负责这一点,以及传说。
g = sns.FacetGrid(tips, col="time", height=4, aspect=.7)
g.map_dataframe(sns.boxplot, x="sex", y="total_bill", hue="smoker",
palette=["#FFA7A0", "#ABEAC9"])
g.map_dataframe(sns.stripplot, x="sex", y="total_bill", hue="smoker",
palette=["#404040"], alpha=0.6, dodge=True)
# Note: the default legend is not resulting in the correct entries.
# Some fix-up step is required here...
# g.add_legend()
plt.show()