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 fromxytexttoxy(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
xycorrectly, causing the annotation to point to the wrong place. - Forgetting to use
arrowpropsif you want an arrow, so the annotation text floats without connection. - Placing
xytexttoo 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
| Parameter | Description | Example |
|---|---|---|
| text | Text string to display | 'Peak value' |
| xy | Point to annotate (x, y) | (2, 5) |
| xytext | Position for text (x, y) | (3, 6) |
| arrowprops | Arrow style dictionary | {'facecolor':'blue', 'shrink':0.05} |
| fontsize | Font size of annotation text | 12 |
| color | Color 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.