#46 Add text annotation on scatterplot

Basic scatterplot

import pandas as pd
import numpy as np
import matplotlib.pylab as plt
import seaborn as sns

# Create dataframe
df = pd.DataFrame({
'x': [1, 1.5, 3, 4, 5],
'y': [5, 15, 5, 10, 2],
'group': ['A','other group','B','C','D']
})

sns.regplot(data=df, x="x", y="y", fit_reg=False, marker="+", color="skyblue")
#sns.plt.show()
Add one annotation

Once you have the data frame, make the plot, and use the text function to add an annotation. You have to provide the x coordinate first, and the y right after.


# basic plot
p1=sns.regplot(data=df, x="x", y="y", fit_reg=False, marker="o", color="skyblue", scatter_kws={'s':400})

# add text annotation
p1.text(3+0.2, 4.5, "An annotation", horizontalalignment='left', size='medium', color='black', weight='semibold')
#sns.plt.show()
Use a loop to annotate each marker

If you want to annotate every markers, it is practical to use a loop as follow:


# basic plot
p1=sns.regplot(data=df, x="x", y="y", fit_reg=False, marker="o", color="skyblue", scatter_kws={'s':400})

# add annotations one by one with a loop
for line in range(0,df.shape[0]):
     p1.text(df.x[line]+0.2, df.y[line], df.group[line], horizontalalignment='left', size='medium', color='black', weight='semibold')

# see it
#sns.plt.show()

Leave a Reply

Your email address will not be published.