ter*_*ina 6 python plot data-visualization seaborn
我有一个使用以下命令创建的箱线图:
sns.boxplot(y='points_per_block', x='block', data=data, hue='habit_trial')
Run Code Online (Sandbox Code Playgroud)
因此不同的颜色代表试验是否是习惯试验(0,1)。我还想绘制各个数据点,我尝试使用以下方法来实现:
sns.stripplot(y='points_per_block', x='block', data=data, hue='habit_trial')
Run Code Online (Sandbox Code Playgroud)
结果如下
我希望各个点显示在相应的箱线图上。有没有一种方法可以做到这一点,而不需要以某种方式侵入他们的位置?问题来自于这样一个事实,即使用色调分离数据对于带状图和箱线图的工作方式不同,但我认为它们很容易组合。
提前致谢。
Joh*_*anC 11
处理分类数据的 Seaborn 函数通常有一个dodge=参数,指示不同色调的数据是否应该稍微分开。对于boxplot,dodge默认为True,因为如果不躲避,它通常会看起来很糟糕。对于stripplot默认为dodge=False.
以下示例还显示了如何更新图例(需要 matplotlib 3.4 HandlerTuple):
import seaborn as sns
from matplotlib.legend_handler import HandlerTuple
tips = sns.load_dataset("tips")
ax = sns.boxplot(data=tips, x="day", y="total_bill",
hue="smoker", hue_order=['Yes', 'No'], boxprops={'alpha': 0.4})
sns.stripplot(data=tips, x="day", y="total_bill",
hue="smoker", hue_order=['Yes', 'No'], dodge=True, ax=ax)
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles=[(handles[0], handles[2]), (handles[1], handles[3])],
labels=['Smoker', 'Non-smoker'],
loc='upper left', handlelength=4,
handler_map={tuple: HandlerTuple(ndivide=None)})
Run Code Online (Sandbox Code Playgroud)