【问题标题】:Combine (overlay) two factorplots in matplotlib在 matplotlib 中组合(叠加)两个因子图
【发布时间】:2018-04-02 13:15:32
【问题描述】:

我需要在 matplotlib 中将swarmplot 添加到boxplot,但我不知道如何使用factorplot。我想我可以使用子图进行迭代,但我想学习如何使用 seaborn 和 factorplot 进行迭代。

一个简单的example(使用同一轴绘制ax):

import seaborn as sns
tips = sns.load_dataset("tips")
ax = sns.boxplot(x="tip", y="day", data=tips, whis=np.inf)
ax = sns.swarmplot(x="tip", y="day", data=tips, color=".2")

结果:

在我的情况下,我需要覆盖群体因子图:

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

和箱线图

我不知道如何使用坐标轴(摘自g)?

类似:

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

我想要这样的东西,但用 factorplot 和 boxplot 而不是 violinplot

【问题讨论】:

  • 您需要 2 个箱线图,因为您有两个 swarmplot,对吗?直接画两个swarmplots和两个boxplots可以轻松叠加不是更有意义吗?
  • @ImportanceOfBeingErnest,绝对!我想要完全按照你的建议,但我正在努力做到这一点。有什么简单的解决方法吗?
  • 编辑令人困惑。您显示的想要拥有的情节只有一个子情节?

标签: python matplotlib seaborn boxplot swarmplot


【解决方案1】:

与其尝试用单独的箱线图覆盖因子图的两个子图(这是可能的,但我不喜欢它),不如单独创建两个子图。

然后,您将遍历组和轴,并为每个绘制一对 box- 和 swarmplot。

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

tips = sns.load_dataset("tips")

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

for ax, (n,grp) in zip(axes, tips.groupby("time")):
    sns.boxplot(x="sex", y="total_bill", data=grp, whis=np.inf, ax=ax)
    sns.swarmplot(x="sex", y="total_bill", hue="smoker", data=grp, 
                  palette=["crimson","indigo"], ax=ax)
    ax.set_title(n)
axes[-1].get_legend().remove()
plt.show()

【讨论】:

  • 太棒了!你只是读懂了我的心思。这正是我需要并努力了几个小时的东西:(非常感谢!!!
猜你喜欢
  • 2020-03-03
  • 1970-01-01
  • 2023-01-20
  • 2020-04-07
  • 2014-09-10
  • 2015-02-08
  • 2021-11-30
  • 1970-01-01
  • 2022-11-04
相关资源
最近更新 更多