0

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

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
  • 1
    Since you are representing spectral/continuous values, I suggest you use a colorbar. See https://stackoverflow.com/a/62886158/13525512 – Tranbi Mar 01 '23 at 12:29

1 Answers1

0

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

JohanC
  • 71,591
  • 8
  • 33
  • 66