0
0
Matplotlibdata~5 mins

Highlight and annotate pattern in Matplotlib

Choose your learning style9 modes available
Introduction

Highlighting and annotating helps to point out important parts of a chart. It makes data easier to understand.

You want to show a key point in a line chart, like a peak or drop.
You need to explain a special event on a graph, like a holiday or sale.
You want to draw attention to a specific data point in a scatter plot.
You want to mark a range on a bar chart to show a target area.
Syntax
Matplotlib
import matplotlib.pyplot as plt

plt.plot(x, y)
plt.annotate('text', xy=(x_point, y_point), xytext=(x_text, y_text), arrowprops=dict(facecolor='color'))
plt.show()

annotate adds text with an arrow pointing to a data point.

xy is the point to highlight, xytext is where the text appears.

Examples
This example highlights the highest point on the line with a red arrow and label 'Peak'.
Matplotlib
import matplotlib.pyplot as plt

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

plt.plot(x, y)
plt.annotate('Peak', xy=(5, 11), xytext=(3, 10), arrowprops=dict(facecolor='red'))
plt.show()
This example points to the value at x=3 with a blue arrow and label.
Matplotlib
import matplotlib.pyplot as plt

x = [0, 1, 2, 3, 4]
y = [1, 4, 9, 16, 25]

plt.plot(x, y)
plt.annotate('Square of 3', xy=(3, 9), xytext=(1, 20), arrowprops=dict(facecolor='blue'))
plt.show()
Sample Program

This program plots a simple line with points. It highlights the point at x=3, y=6 with a green arrow and label.

Matplotlib
import matplotlib.pyplot as plt

# Data for plotting
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

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

# Highlight the point where x=3
plt.annotate('Important Point', xy=(3, 6), xytext=(4, 7),
             arrowprops=dict(facecolor='green', shrink=0.05))

plt.title('Highlight and Annotate Example')
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.grid(True)
plt.show()
OutputSuccess
Important Notes

You can customize arrow colors and styles using arrowprops.

Use xytext to place the annotation text where it does not block the data.

Adding marker='o' helps to see exact data points.

Summary

Use plt.annotate() to add labels and arrows to highlight data points.

Choose xy for the point and xytext for the label position.

Customize arrows with arrowprops for better visuals.