Legend from seaborn box-plot disrupts the alignment with overlayed swarm-plot

231 Views Asked by At

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?

1

There are 1 best solutions below

0
jylls On

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