pythonplotseabornscatter-plot

Adding labels in x y scatter plot with seaborn


I've spent hours on trying to do what I thought was a simple task, which is to add labels onto an XY plot while using seaborn.

Here's my code:

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

sns.lmplot('sepal_length', # Horizontal axis
           'sepal_width', # Vertical axis
           data=df_iris, # Data source
           fit_reg=False, # Don't fix a regression line
           size = 8,
           aspect =2 ) # size and dimension

plt.title('Example Plot')
# Set x-axis label
plt.xlabel('Sepal Length')
# Set y-axis label
plt.ylabel('Sepal Width')

I would like to add to each dot on the plot the text in "species" column.

I've seen many examples using matplotlib but not using seaborn.


Solution

  • The following implementation will label each point with its respective species:

    import seaborn as sns
    import matplotlib.pyplot as plt
    import pandas as pd
        
    df = sns.load_dataset("iris") 
    
    ax = sns.lmplot(x='sepal_length', # Horizontal axis
                    y='sepal_width', # Vertical axis
                    data=df, # Data source
                    fit_reg=False, # Don't fix a regression line
                    aspect=2) # size and dimension
    
    plt.title('Example Plot')
    # Set x-axis label
    plt.xlabel('Sepal Length')
    # Set y-axis label
    plt.ylabel('Sepal Width')
    
    
    def label_point(x, y, val, ax):
        a = pd.concat({'x': x, 'y': y, 'val': val}, axis=1)
        for i, point in a.iterrows():
            ax.text(point['x']+.02, point['y'], str(point['val']))
    
    label_point(df.sepal_length, df.sepal_width, df.species, plt.gca()) 
    

    enter image description here