data visualization
plot annotations
interactive plots
data analysis tools
chart enhancements

Matplotlib hover tooltips: add hovering annotations to a plot

Codemia Knowledge Hub ·

In Matplotlib, the easiest way to show a tooltip when the mouse is over a point is mplcursors.cursor(artist, hover=True). Browser-oriented libraries such as Plotly have hover built in. Hover annotations keep dense time series and scatter plots clean while still exposing exact values on demand.

Matplotlib hover with mplcursors

python
1import numpy as np
2import matplotlib.pyplot as plt
3import mplcursors
4
5x = np.linspace(0, 10, 25)
6y = np.sin(x)
7
8fig, ax = plt.subplots(figsize=(7, 4))
9line, = ax.plot(x, y, marker="o", label="sin(x)")
10ax.legend()
11ax.set_title("Hover annotation demo")
12
13cursor = mplcursors.cursor(line, hover=True)
14
15@cursor.connect("add")
16def on_add(selection):
17    x_value, y_value = selection.target
18    selection.annotation.set_text(
19        f"x = {x_value:.2f}\ny = {y_value:.2f}"
20    )
21
22plt.show()

The cursor attaches to the plotted artist and creates the tooltip when the mouse moves over a point.

Plotly's built-in hover

For notebooks, dashboards or HTML output, Plotly is often simpler because hover is native.

python
1import pandas as pd
2import plotly.express as px
3
4df = pd.DataFrame(
5    {
6        "step": [1, 2, 3, 4, 5],
7        "loss": [0.95, 0.73, 0.58, 0.49, 0.44],
8        "run": ["A", "A", "A", "A", "A"],
9    }
10)
11
12fig = px.line(df, x="step", y="loss", markers=True, title="Training loss")
13fig.update_traces(
14    hovertemplate="step=%{x}<br>loss=%{y:.3f}<extra></extra>"
15)
16fig.show()

hovertemplate controls the formatting exactly, and <extra></extra> hides the default extra label block.

Keeping hover text short

Show the key x value, y value and, when needed, one identifying field such as the series name. A tooltip that reads like a database record makes the chart harder to use.

On multi-series plots, show the series label explicitly, or two nearby lines are hard to tell apart:

python
1import numpy as np
2import matplotlib.pyplot as plt
3import mplcursors
4
5x = np.arange(1, 6)
6a = np.array([10, 12, 11, 15, 16])
7b = np.array([8, 9, 10, 10, 12])
8
9fig, ax = plt.subplots()
10line_a, = ax.plot(x, a, marker="o", label="Team A")
11line_b, = ax.plot(x, b, marker="s", label="Team B")
12ax.legend()
13
14cursor = mplcursors.cursor([line_a, line_b], hover=True)
15
16@cursor.connect("add")
17def add_label(selection):
18    label = selection.artist.get_label()
19    x_value, y_value = selection.target
20    selection.annotation.set_text(
21        f"{label}\nweek = {x_value:.0f}\nvalue = {y_value:.1f}"
22    )
23
24plt.show()

Why the tooltip never appears

  • Non-interactive backend. Matplotlib hover callbacks need an interactive backend. When you save a PNG or run in a non-interactive environment, no hover event fires: the code runs but nothing shows. Browser-based libraries are easier for dashboards and shareable reports. For a static report, use regular annotations or labels instead.
  • Wrong artist. The cursor must target the plotted object that receives the interaction.

Large datasets, long tooltips and accessibility

Hover gets sluggish when a chart has huge numbers of points. If the plot is for exploration rather than exact rendering of every sample, downsample or aggregate, or show hover details only for sampled points or highlighted subsets.

A tooltip that covers nearby points or spans half the plot is counterproductive. And hover-only information can create accessibility problems, so make important values available through other UI or reporting paths when needed.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design