How to Annotate Matplotlib Scatterplots


A scatterplot is a useful way to visualize the relationship between two variables.

Fortunately it’s easy to create scatterplots in Matplotlib by using the matplotlib.pyplot.scatter() function.

It’s also easy to add annotations or text to scatterplots by using the annotate() and text() functions. This tutorial shows how to use these functions in practice.

Create Basic Scatterplot

The following code shows how to create a basic scatterplot using Matplotlib:

import matplotlib.pyplot as plt

#create data
x = [3, 6, 8, 12, 14]
y = [4, 9, 14, 12, 9]

#create scatterplot
plt.scatter(x, y)

Annotate a Single Point

We can use the following code to add an annotation to a single point in the plot:

import matplotlib.pyplot as plt

#create data
x = [3, 6, 8, 12, 14]
y = [4, 9, 14, 12, 9]

#create scatterplot
plt.scatter(x, y)

#add text 'Here' at (x, y) coordinates = (6, 9.5)
plt.text(6, 9.5, 'Here')

Scatterplot with annotation in Matplotlib

Annotate Multiple Points

We can use the following code to add annotations to multiple points in the plot:

import matplotlib.pyplot as plt

#create data
x = [3, 6, 8, 12, 14]
y = [4, 9, 14, 12, 9]

#create scatterplot
plt.scatter(x, y)

#add text to certain points
plt.text(3, 4.5, 'This')
plt.text(6, 9.5, 'That')
plt.text(8.2, 14, 'Those')

Annotate multiple points on Matplotlib scatterplot

Annotate All Points

We can use the following code to add annotations to every single point in the plot:

import matplotlib.pyplot as plt

#create data
x = [3, 6, 8, 12, 14]
y = [4, 9, 14, 12, 9]
labs = ['A', 'B', 'C', 'D', 'E']

#create scatterplot
plt.scatter(x, y)

#use for loop to add annotations to each point in plot 
for i, txt in enumerate(labs):
    plt.annotate(txt, (x[i], y[i]))

Annotate Matplotlib scatterplot

By default, the annotations are placed directly on top of the points in the scatterplot and the default font size is 10.

The following code shows how to adjust both of these settings so the annotations are slightly to the right of the points and the font size is slightly larger:

import matplotlib.pyplot as plt

#create data
x = [3, 6, 8, 12, 14]
y = [4, 9, 14, 12, 9]
labs = ['A', 'B', 'C', 'D', 'E']

#create scatterplot
plt.scatter(x, y)

#use for loop to add annotations to each point in plot 
for i, txt in enumerate(labs):
    plt.annotate(txt, (x[i]+.25, y[i]), fontsize=12)

Matplotlib annotate every point in plot

You can find more Matplotlib tutorials here.

Leave a Reply

Your email address will not be published. Required fields are marked *