如何在seaborn中将箱线图显示在小提琴图前面- seaborn zorder?

4

为自定义显示在小提琴图内的箱形图样式,可以尝试在小提琴图前绘制一个箱形图。但是,当使用seaborn时,这似乎不起作用,因为它总是显示在小提琴图的后面。

当使用seaborn + matplotlib时,这可以工作(但仅适用于单个类别):

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

df=pd.DataFrame(np.random.rand(10,2)).melt(var_name='group')

fig, axes = plt.subplots()

# Seaborn violin plot
sns.violinplot(y=df[df['group']==0]['value'], color="#af52f4", inner=None, linewidth=0, saturation=0.5)

# Normal boxplot has full range, same in Seaborn boxplot
axes.boxplot(df[df['group']==0]['value'], whis='range', positions=np.array([0]),
            showcaps=False,widths=0.06, patch_artist=True,
            boxprops=dict(color="indigo", facecolor="indigo"),
            whiskerprops=dict(color="indigo", linewidth=2),
            medianprops=dict(color="w", linewidth=2 ))

axes.set_xlim(-1,1)

plt.show()

正确放置的箱线图

但是,当只使用seaborn跨多个类别绘制图表时,排序总是错误的:

sns.violinplot(data=df, x='group', y='value', color="#af52f4", inner=None, linewidth=0, saturation=0.5)
sns.boxplot(data=df, x='group', y='value', saturation=0.5)


plt.show()

错误放置的箱形图

即使尝试使用zorder修复,这也不起作用。

1个回答

8
sns.boxplotzorder参数仅影响箱线图的线条,而不影响矩形框。一种可能是在之后访问这些框;它们形成ax.artists中的艺术家列表。将它们的zorder=2设置为将它们放在小提琴前面,同时仍然在其他箱线图线条后面。
在评论中,@mwaskom指出了更好的方法。 sns.boxplot通过**kwargs委托所有未识别的参数到ax.boxplot。其中之一是具有盒子矩形属性的boxprops。因此,boxprops={'zorder': 2}将仅更改框的zorder
以下是一个示例:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.rand(10, 2)).melt(var_name='group')
ax = sns.violinplot(data=df, x='group', y='value', color="#af52f4", inner=None, linewidth=0, saturation=0.5)
sns.boxplot(data=df, x='group', y='value', saturation=0.5, width=0.4,
            palette='rocket', boxprops={'zorder': 2}, ax=ax)
plt.show()

sns.boxplot in front of sns.violinplot

这是另一个例子,使用tips数据集:

tips = sns.load_dataset('tips')
ax = sns.violinplot(data=tips, x='day', y='total_bill', palette='turbo',
                    inner=None, linewidth=0, saturation=0.4)
sns.boxplot(x='day', y='total_bill', data=tips, palette='turbo', width=0.3,
            boxprops={'zorder': 2}, ax=ax)

seaborn violinplot with boxplot for tips dataset


4
更好的做法是将boxprops={"zorder": 2}传递给boxplot函数,这样您就不需要与艺术家列表打交道了。 - mwaskom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接