要自定义显示在小提琴图内的箱线图的样式,可以尝试在小提琴图前绘制箱线图。然而,这似乎不起作用,因为它在使用 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
解决此问题,这也不起作用。
答案 0 :(得分:2)
sns.boxplot
的 zorder
参数仅影响箱线图的线条,而不影响矩形框。
一种可能性是事后访问这些盒子;它们构成了 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()
这是另一个示例,使用 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)