Search code examples
seabornscatter-plot

Seaborn Scatter plot custom legend showing Single Label


I used the below code to plot a scatter plot using seaborn. I need to change the labels text in legend. But when I add custom text for the legends, it's only showing one label. I need to have legend text as ['set', 'versi', 'vir']. The code is as below -

import seaborn as sns
import matplotlib.pyplot as plt
iris = sns.load_dataset("iris")

scatter = sns.scatterplot(x='sepal_length', y ='sepal_width', hue='species', data=iris, legend=False)
scatter.legend(labels = ['set', 'versi', 'vir'], loc='upper right')
plt.show(scatter)

enter image description here


Solution

  • Seaborn's sophisticated way of working can't always follow the rules needed for a standard legend (see e.g. issue 2280). Often, the legend is custom created. Currently, matplotlib doesn't provide simple functions to move (or alter) such a legend.

    In seaborn 0.11.2, a function sns.move_legend(ax, ...) (info on github) is added, which can move the legend and change some other properties (but not the labels).

    So, you can first let sns.scatterplot create a legend, and then move it.

    The labels in the legend come from the element names in the hue-column. To obtain different names, the most straightforward way is to temporarily rename them.

    Here is some example code (note that plt.show() doesn't have an ax as parameter, but does have an optional block= parameter):

    import seaborn as sns
    import matplotlib.pyplot as plt
    
    iris = sns.load_dataset("iris")
    
    ax = sns.scatterplot(x='sepal_length', y='sepal_width', hue='species',
                         data=iris.replace({'species': {'setosa': 'set', 'versicolor': 'versi', 'virginica': 'vir'}}))
    sns.move_legend(ax, loc='upper right')
    plt.show()
    

    sns.scatterplot with moved and renamed legend