处理分类数据的 Seaborn 函数通常具有dodge=
参数指示不同色调的数据是否应该分开一点。为一个boxplot
, dodge
默认为True
,因为如果不躲闪,通常会看起来很糟糕。为一个stripplot
默认为dodge=False
.
以下示例还展示了如何更新图例(需要 matplotlib 3.4HandlerTuple
):
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)})