Add text annotation on scatterplot


This post provides several examples with reproducible code showing how to use text() function of matplotlib to add text annotations on the plot.

Basic scatterplot

You can create a basic scatterplot using regplot() function of seaborn library. The following parameters should be provided:

  • data : dataset
  • x : positions of points on the X axis
  • y : positions of points on the Y axis
  • fit_reg : if True, show the linear regression fit line
  • marker : marker shape
  • color : the color of markers
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")

plt.show()

Add one annotation

Once you have created the dataset and plotted the scatterplot with the previous code, you can use text() function of matplotlib to add annotation. The following parameters should be provided:

  • x : the position to place the text in x axis
  • y : the position to place the text in y axis
  • s: the text

You can also specify the additional parameters such as horizontalalignment, size, color, weight to design your text.

# basic plot
sns.regplot(data=df, x="x", y="y", fit_reg=False, marker="o", color="skyblue", scatter_kws={'s':400})
 
# add text annotation
plt.text(3+0.2, 4.5, "An annotation", horizontalalignment='left', size='medium', color='black', weight='semibold')

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
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]):
     plt.text(df.x[line]+0.2, df.y[line], df.group[line], horizontalalignment='left', size='medium', color='black', weight='semibold')

plt.show()

Scatterplot

Heatmap

Correlogram

Bubble

Connected Scatter

2D Density

Contact & Edit

👋 This document is a work by Yan Holtz. Any feedback is highly encouraged. You can fill an issue on Github, drop me a message onTwitter, or send an email pasting yan.holtz.data with gmail.com.

This page is just a jupyter notebook, you can edit it here. Please help me making this website better 🙏!

Violin

Density

Histogram

Boxplot

Ridgeline

Scatterplot

Heatmap

Correlogram

Bubble

Connected Scatter

2D Density

Barplot

Spider / Radar

Wordcloud

Parallel

Lollipop

Circular Barplot

Treemap

Venn Diagram

Donut

Pie Chart

Dendrogram

Circular Packing

Line chart

Area chart

Stacked Area

Streamgraph

Map

Choropleth

Hexbin

Cartogram

Connection

Bubble

Chord Diagram

Network

Sankey

Arc Diagram

Edge Bundling

Colors

Interactivity

Animation with python

Animation

Cheat sheets

Caveats

3D