0
0
Matplotlibdata~5 mins

Annotating specific points in Matplotlib

Choose your learning style9 modes available
Introduction

We add notes or labels to important points on a graph to explain what they mean. This helps people understand the story behind the data.

You want to highlight the highest or lowest value in a chart.
You need to explain a special event or outlier in your data.
You want to add extra information about a point on a scatter plot.
You want to make your graph easier to understand for others.
Syntax
Matplotlib
plt.annotate(text, xy, xytext=None, arrowprops=None, **kwargs)

text is the label you want to show.

xy is the point (x, y) you want to annotate.

Examples
Adds a label 'Max value' at the point (5, 10) on the plot.
Matplotlib
plt.annotate('Max value', xy=(5, 10))
Adds a label 'Peak' with an arrow pointing from (4, 8) to (3, 7).
Matplotlib
plt.annotate('Peak', xy=(3, 7), xytext=(4, 8), arrowprops=dict(facecolor='black'))
Sample Program

This code plots points and adds a label with an arrow to the highest point (5, 11). The label is placed near the point with an arrow pointing to it.

Matplotlib
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]

plt.plot(x, y, marker='o')

# Annotate the highest point
max_x = x[-1]
max_y = y[-1]
plt.annotate('Highest point', xy=(max_x, max_y), xytext=(max_x-1, max_y+1), arrowprops=dict(facecolor='blue', shrink=0.05))

plt.title('Annotating Specific Points Example')
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.grid(True)
plt.show()
OutputSuccess
Important Notes

You can customize the arrow style and text position to make annotations clear.

Annotations help make your graphs more informative and easier to understand.

Summary

Annotations add labels to specific points on a plot.

Use plt.annotate() with the point coordinates and label text.

Arrows can point from the label to the point for clarity.