0
0
Matplotlibdata~5 mins

Text annotations in Matplotlib

Choose your learning style9 modes available
Introduction

Text annotations help you add notes or labels to specific points on a plot. This makes your charts easier to understand.

You want to highlight a peak or important point in a line chart.
You need to explain a special event on a timeline graph.
You want to label a specific data point in a scatter plot.
You want to add extra information without changing the main title or axis labels.
Syntax
Matplotlib
plt.annotate(text, xy, xytext=None, arrowprops=None, **kwargs)

text is the string you want to show.

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

Examples
Adds a simple label at point (2, 8).
Matplotlib
plt.annotate('Max value', xy=(2, 8))
Adds a label 'Peak' at (3, 10) with an arrow pointing from text at (4, 12).
Matplotlib
plt.annotate('Peak', xy=(3, 10), xytext=(4, 12), arrowprops=dict(facecolor='black'))
Sample Program

This code plots points and adds an annotation to the highest point with an arrow and label.

Matplotlib
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 8, 10, 6, 4]

plt.plot(x, y, marker='o')
plt.title('Sample Plot with Annotation')

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

plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.grid(True)
plt.show()
OutputSuccess
Important Notes

You can customize the arrow style and text font using arrowprops and other keyword arguments.

If you don't specify xytext, the text will appear exactly at xy.

Annotations help make your plots more informative and easier to read.

Summary

Use plt.annotate() to add text labels to specific points on a plot.

You can add arrows to point from the label to the data point.

Annotations improve the clarity and storytelling of your charts.