0

edit: solved here

seaborn boxplot and stripplot points aren't aligned over the x-axis by hue

In the above case, the swarmplot was shifted in the overlay and the resolution was achieved from setting dodge = true in swarmplot.

Here, the boxplot was shifted, the resolution was achieved from setting dodge = False in barplot.


I have a seaborn boxplot overlayed with a seaborn swarmplot. Whenever I add labels to my boxplot, the legend repositions the boxplot without adjusting the swarmplot (fig 1). Fig1

sns.swarmplot(x = 'data_type', y = 'count', data = df, 
                   alpha = .5, palette='colorblind', hue='data_type', legend = 0, zorder=0.5)


ax = sns.boxplot(x = 'data_type', y = 'count', data = df,
                 palette='colorblind', showfliers = 0, hue = 'data_type')

plt.legend(bbox_to_anchor = (1.02, 1), loc = 'upper left')

If I remove the labels, through omitting hue = 'data_type' then I have the alignment I want (fig 2). Fig2

How can I display the boxplot legend while preserving alignment?

  • `ax = sns.swarmplot(…)` then `sns.boxplot(…, ax=ax)` and `ax.legend(…)` – Trenton McKinney Mar 29 '23 at 18:58
  • Additionally, it is redundant and unnecessary to use `hue` because the labels are already on the x-axis. – Trenton McKinney Mar 29 '23 at 19:02
  • @jylls [it](https://stackoverflow.com/questions/75880582/legend-from-seaborn-box-plot-disrupts-the-alignment-with-overlayed-swarm-plot?noredirect=1#comment133844744_75880582) shows the correct way to assign and reuse the matplotlib.axes returned by seaborn. The duplicates already explain dodge and hue. – Trenton McKinney Mar 29 '23 at 19:56

1 Answers1

1

It looks like you need to set dodge=False when calling the boxplot function. See doc here for more info and see code below:

import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset("tips")
fig,ax=plt.subplots()
sns.swarmplot(data=tips,x="day",y="total_bill",hue='day',legend=0,ax=ax)
sns.boxplot(data=tips,x="day", y="total_bill",hue='day',showfliers = 0,ax=ax,dodge=False)
plt.legend(bbox_to_anchor = (1.02, 1), loc = 'upper left')

enter image description here

jylls
  • 4,395
  • 2
  • 10
  • 21