0
0
Matplotlibdata~5 mins

Annotation with arrows in Matplotlib

Choose your learning style9 modes available
Introduction

We use annotations with arrows to point out important parts of a chart. It helps make the chart easier to understand.

You want to highlight a peak or valley in a line chart.
You need to explain a special point on a scatter plot.
You want to add notes to a bar chart to show extra info.
You want to guide the viewerโ€™s attention to a specific data point.
You want to label parts of a plot clearly with arrows.
Syntax
Matplotlib
plt.annotate(text, xy, xytext=None, arrowprops=None, **kwargs)

text is the label string you want to show.

xy is the point (x, y) to point at with the arrow.

Examples
This adds an annotation 'Peak' pointing to (2, 8) with the text shown at (3, 10).
Matplotlib
plt.annotate('Peak', xy=(2, 8), xytext=(3, 10), arrowprops=dict(facecolor='black'))
Annotation with default text position and a simple arrow style.
Matplotlib
plt.annotate('Important', xy=(1, 5), arrowprops=dict(arrowstyle='->'))
Arrow with red color and a small shrink effect near the point.
Matplotlib
plt.annotate('Note', xy=(4, 7), xytext=(5, 9), arrowprops=dict(color='red', shrink=0.05))
Sample Program

This code plots a line with points and adds an annotation with an arrow pointing to the highest point on the line.

Matplotlib
import matplotlib.pyplot as plt

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

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

# 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='blue', shrink=0.05))

plt.title('Line plot with annotation')
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.grid(True)
plt.show()
OutputSuccess
Important Notes

You can customize arrow styles using arrowprops dictionary.

If xytext is not given, the text appears at the point xy.

Use shrink in arrowprops to adjust arrow length near the point.

Summary

Annotations with arrows help explain charts clearly.

Use plt.annotate() with xy and arrowprops to add arrows.

You can place text separately from the arrow tip using xytext.