0
0
MatplotlibHow-ToBeginner ยท 3 min read

How to Add Annotation in Matplotlib: Simple Guide

Use the annotate() function in Matplotlib to add text annotations to plots. It requires the text, the point to annotate, and optionally the point to place the text, allowing you to highlight specific data points clearly.
๐Ÿ“

Syntax

The basic syntax of annotate() in Matplotlib is:

  • text: The string to display as annotation.
  • xy: The point (x, y) to annotate.
  • xytext: The position (x, y) to place the annotation text (optional).
  • arrowprops: Dictionary to draw an arrow from xytext to xy (optional).
python
plt.annotate(text, xy, xytext=None, arrowprops=None, **kwargs)
๐Ÿ’ป

Example

This example shows how to annotate a point on a simple line plot with an arrow pointing to it.

python
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 point (3, 5)
plt.annotate('Prime number 5', xy=(3, 5), xytext=(4, 6),
             arrowprops=dict(facecolor='black', shrink=0.05))

plt.title('Example of Annotation in Matplotlib')
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.show()
Output
A line plot with points marked; the point at x=3, y=5 is labeled 'Prime number 5' with an arrow pointing to it.
โš ๏ธ

Common Pitfalls

Common mistakes when adding annotations include:

  • Not specifying xy correctly, causing the annotation to point to the wrong place.
  • Forgetting to use arrowprops if you want an arrow, so the annotation text floats without connection.
  • Placing xytext too close or overlapping the point, making the annotation hard to read.

Always check coordinates and adjust xytext for clarity.

python
import matplotlib.pyplot as plt

x = [1, 2, 3]
y = [1, 4, 9]

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

# Wrong: No arrow, annotation text overlaps point
plt.annotate('Square 9', xy=(3, 9), xytext=(3, 9))

# Correct: Arrow added and text moved
plt.annotate('Square 9', xy=(3, 9), xytext=(2, 8),
             arrowprops=dict(facecolor='red', shrink=0.05))

plt.show()
Output
A plot with three points; the annotation 'Square 9' first overlaps the point without arrow, then correctly shows an arrow pointing from text to point.
๐Ÿ“Š

Quick Reference

ParameterDescriptionExample
textText string to display'Peak value'
xyPoint to annotate (x, y)(2, 5)
xytextPosition for text (x, y)(3, 6)
arrowpropsArrow style dictionary{'facecolor':'blue', 'shrink':0.05}
fontsizeFont size of annotation text12
colorColor of annotation text'green'
โœ…

Key Takeaways

Use plt.annotate() with text and xy parameters to add annotations.
Use xytext and arrowprops to position text and draw arrows for clarity.
Check coordinates carefully to avoid overlapping or misplaced annotations.
Customize annotation style with font size, color, and arrow properties.
Annotations help highlight important points clearly on your plots.