How To Do A Boxplot With Individual Data Points Using Seaborn
I have a box plot that I create using the following command: sns.boxplot(y='points_per_block', x='block', data=data, hue='habit_trial') So the different colors represent whether t
Solution 1:
Seaborn functions working with categorical data usually have a dodge=
parameter indicating whether data with different hue should be separated a bit. For a boxplot
, dodge
defaults to True
, as it usually would look bad without dodging. For a stripplot
defaults to dodge=False
.
The following example also shows how the legend can be updated (matplotlib 3.4 is needed for 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)})
Post a Comment for "How To Do A Boxplot With Individual Data Points Using Seaborn"