0
0
Matplotlibdata~5 mins

Mplcursors for hover labels in Matplotlib

Choose your learning style9 modes available
Introduction

Mplcursors lets you add labels that appear when you hover over points on a plot. This helps you see details without cluttering the graph.

You want to show extra info about points only when the mouse is over them.
You have a scatter plot and want to display values interactively.
You want to explore data points in a plot without adding static text.
You need a simple way to add interactive labels in matplotlib plots.
Syntax
Matplotlib
import mplcursors

cursor = mplcursors.cursor(plot_elements)
cursor.connect("add", lambda sel: sel.annotation.set_text('your label text'))

mplcursors.cursor() activates hover labels on given plot elements like lines or scatter points.

The connect method lets you customize the label text when hovering.

Examples
This example shows hover labels on scatter points displaying their coordinates.
Matplotlib
import matplotlib.pyplot as plt
import mplcursors

fig, ax = plt.subplots()
points = ax.scatter([1, 2, 3], [4, 5, 6])

cursor = mplcursors.cursor(points)
cursor.connect("add", lambda sel: sel.annotation.set_text(f"Point: {sel.target}"))

plt.show()
Hover labels on a line plot show the index and y-value of each point.
Matplotlib
import matplotlib.pyplot as plt
import mplcursors

fig, ax = plt.subplots()
line, = ax.plot([1, 2, 3], [4, 5, 6], marker='o')

cursor = mplcursors.cursor(line)
cursor.connect("add", lambda sel: sel.annotation.set_text(f"Index: {sel.index}\nValue: {sel.target[1]}"))

plt.show()
Sample Program

This program creates a scatter plot and shows x and y values when you hover over each point.

Matplotlib
import matplotlib.pyplot as plt
import mplcursors

# Create a scatter plot
fig, ax = plt.subplots()
x = [10, 20, 30, 40]
y = [1, 4, 9, 16]
scatter = ax.scatter(x, y)

# Add hover labels showing x and y values
cursor = mplcursors.cursor(scatter)
cursor.connect("add", lambda sel: sel.annotation.set_text(f"x={sel.target[0]}\ny={sel.target[1]}"))

plt.title('Scatter plot with hover labels')
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.show()
OutputSuccess
Important Notes

Make sure you have mplcursors installed: run pip install mplcursors.

Hover labels only appear when you move the mouse over the plot points.

You can customize the label text fully using the connect method.

Summary

Mplcursors adds interactive hover labels to matplotlib plots.

Use it to show details about points without cluttering the graph.

Customize labels easily with a simple function.