Search code examples
seabornpython-3.7scatter-plot

Is there any way to change the legends in seaborn?


I would like to change the format of pIC50 in the legend box. I would like it to be "circle according to the size with no filled color". Any suggestions are welcome!

plt.figure(figsize=(7, 7))

sns.scatterplot(x='MW', y='LogP', data=df_2class, hue='class', size='pIC50', edgecolor='black', alpha=0.2)
sns.set_style("whitegrid", {"ytick.major.size": 100,"xtick.major.size": 2, 'grid.linestyle': 'solid'})

plt.xlabel('MW', fontsize=14, fontweight='bold')
plt.ylabel('LogP', fontsize=14, fontweight='bold')
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0)

enter image description here


Solution

  • In this case, you can loop through the last legend handles and change the color of the dots. Here is an example using the iris dataset:

    import matplotlib.pyplot as plt
    import seaborn as sns
    
    iris = sns.load_dataset('iris')
    ax = sns.scatterplot(data=iris, x='sepal_length', y='petal_length', hue='species', size='sepal_width')
    handles, labels = ax.get_legend_handles_labels()
    for h in handles[-5:]: # changes the 5 last handles, this number might be different in your case
        h.set_facecolor('none')
    ax.legend(handles=handles, labels=labels, bbox_to_anchor=[1.02, 1.02], loc='upper left')
    plt.tight_layout()
    plt.show()
    

    sns.scatterplot with open dots in the legend