How to show a grouped legend for the hue in a swarmplot

161 Views Asked by At

How can I group the colors shown in the picture below? If I show the legend, I see all the single value color.

ax1=sns.swarmplot(x='y', y='Fos', data=result, color="k", alpha=0.8, hue="y4", palette="Spectral")
plt.title('Y4');
ax1.get_legend().remove() #sns.move_legend(ax, "upper left", bbox_to_anchor=(1, 1))
    
plt.show()

enter image description here

1

There are 1 best solutions below

0
JohanC On

You could create a new column with ranges of the continuous hue values.

Here is an example with seaborn's mpg dataset.

from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd

mpg = sns.load_dataset('mpg')
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(16, 5))
sns.swarmplot(mpg, x='origin', y='weight', hue='mpg', palette='turbo', ax=ax1)
ax1.set_title('Default legend')

mpg['mpg range'] = pd.cut(mpg['mpg'], bins=[0, 20, 30, 40, np.inf],
                          labels=['mpg ≤ 20', '20 < mpg ≤ 30', '30 < mpg ≤ 40', 'mpg > 40'])
sns.swarmplot(mpg, x='origin', y='weight', hue='mpg range', palette='turbo', ax=ax2)
ax2.set_title('Legend with ranges')

plt.tight_layout()
plt.show()

sns.swarmplot legend with ranges