我正在尝试使用matplotlib和Seaborn一起绘制群图和箱形图。我发现了如何将它们绘制在一起,但箱形图出现在群体图的下方。问题在于,群图点淹没了箱形图,箱形图丢失了。我认为,通过切换调用函数的顺序,使箱形图称为第一个而不是第二个,如下面的链接所示,会将箱形图覆盖在顶部,但不会。

是否可以将箱形图叠加在群体图点的顶部?如果不是,是否可以创建表示四分位数位置的线?

代码:

swarm_name = "Swarm_Plot_01"
#
sns.set_style("whitegrid")
ax = sns.boxplot(   data = [df.Rate_VL1R, df.Rate_V12R, df.Rate_V23R, df.Rate_VM3R ],
   showcaps=False,boxprops={'facecolor':'None'},
   showfliers=False,whiskerprops={'linewidth':0})
ax = sns.swarmplot( data = [df.Rate_VL1R, df.Rate_V12R, df.Rate_V23R, df.Rate_VM3R ] )
plt.show()
fig = ax.get_figure()
fig.savefig(swarm_name)
plt.figure()

这个问题与How to create a swarm plot with matplotlib相关,但不完全相同,因为我要更改样式,而不仅仅是将两者放在一起。

python - 如何在西伯恩(Seaborn)的群图中叠加箱形图?-LMLPHP

最佳答案

问题在于箱形图由许多不同的艺术家组成,并且由于深层包装机制,我们不能简单地将完整箱形图的zorder设置为更高的数字。

天真的尝试是将swarmplot的zorder设置为零。虽然这会将swarmplot点放在箱线图的后面,但也将它们放在网格线的后面。因此,如果不使用网格线,则此解决方案是最佳的。

import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")

# plot swarmplot
ax = sns.swarmplot(x="day", y="total_bill", data=tips, zorder=0)
# plot boxplot
sns.boxplot(x="day", y="total_bill", data=tips,
                 showcaps=False,boxprops={'facecolor':'None'},
                 showfliers=False,whiskerprops={'linewidth':0}, ax=ax)

plt.show()

python - 如何在西伯恩(Seaborn)的群图中叠加箱形图?-LMLPHP

如果需要网格线,可以将swarmplot的zorder设置为1,以使其显示在网格线上方,并将boxplot的zorder设置为较高的数字。如上所述,这需要将zorder属性设置为其每个元素,因为zorder=10调用中的boxplot不会影响所有艺术家。相反,我们需要使用boxpropswhiskerprops参数为它们设置zorder正确性。
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")

# plot swarmplot
ax = sns.swarmplot(x="day", y="total_bill", data=tips, zorder=1)
# plot boxplot
sns.boxplot(x="day", y="total_bill", data=tips,
                 showcaps=False,boxprops={'facecolor':'None', "zorder":10},
                 showfliers=False,whiskerprops={'linewidth':0, "zorder":10},
                 ax=ax, zorder=10)

plt.show()

python - 如何在西伯恩(Seaborn)的群图中叠加箱形图?-LMLPHP

最终解决方案(可以在通常情况下根本没有访问艺术家属性的情况下适用)是遍历坐标轴艺术家,并根据他们属于一个绘图区还是另一个绘图区为它们设置zorder。
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")

# plot swarmplot
ax = sns.swarmplot(x="day", y="total_bill", data=tips)
#get all children of axes
children1 = ax.get_children()
# plot boxplot
sns.boxplot(x="day", y="total_bill", data=tips,
                 showcaps=False,boxprops={'facecolor':'None'},
                 showfliers=False,whiskerprops={'linewidth':0}, ax=ax)
# again, get all children of axes.
children2 = ax.get_children()
# now those children which are in children2 but not in children1
# must be part of the boxplot. Set zorder high for those.
for child in children2:
    if not child in children1:
        child.set_zorder(10)

plt.show()

python - 如何在西伯恩(Seaborn)的群图中叠加箱形图?-LMLPHP

关于python - 如何在西伯恩(Seaborn)的群图中叠加箱形图?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44615759/

10-12 12:39