Home > Backend Development > Python Tutorial > How to Create Hovering Annotations in Matplotlib Scatter Plots?

How to Create Hovering Annotations in Matplotlib Scatter Plots?

Mary-Kate Olsen
Release: 2025-01-01 08:54:10
Original
498 people have browsed it

How to Create Hovering Annotations in Matplotlib Scatter Plots?

Hovering Annotations in Matplotlib Scatter Plots

When analyzing scatter plots, it can be useful to view the specific data associated with individual points. By adding annotations that appear on hover, you can quickly identify outliers and other notable points of interest.

Implementation

Using the annotation capabilities of Matplotlib, we can create interactive annotations that only become visible when the cursor hovers near a specific point. The following code demonstrates this approach:

import matplotlib.pyplot as plt
import numpy as np

# Generate random scatter plot data
x = np.random.rand(15)
y = np.random.rand(15)
names = np.array(list("ABCDEFGHIJKLMNO"))

# Create scatter plot and annotation
fig, ax = plt.subplots()
sc = plt.scatter(x, y, c=np.random.randint(1, 5, size=15), s=100)
annot = ax.annotate("", xy=(0, 0), xytext=(20, 20), textcoords="offset points",
                    bbox=dict(boxstyle="round", fc="w"),
                    arrowprops=dict(arrowstyle="->"))
annot.set_visible(False)

# Define hover function to update annotation
def hover(event):
    # Check if hover is within axis and over a point
    if event.inaxes == ax and annot.get_visible():
        cont, ind = sc.contains(event)
        if cont:
            # Update annotation with point data
            pos = sc.get_offsets()[ind["ind"][0]]
            annot.xy = pos
            text = "{}, {}".format(" ".join(list(map(str, ind["ind"]))),
                                   " ".join([names[n] for n in ind["ind"]]))
            # Show annotation and update figure
            annot.set_text(text)
            annot.set_visible(True)
            fig.canvas.draw_idle()
        else:
            # Hide annotation
            annot.set_visible(False)
            fig.canvas.draw_idle()

# Connect hover event to function
fig.canvas.mpl_connect("motion_notify_event", hover)

plt.show()
Copy after login

As you hover over different points in the scatter plot, the annotation will appear and display the associated data, providing quick access to important information without cluttering the plot with permanent labels.

The above is the detailed content of How to Create Hovering Annotations in Matplotlib Scatter Plots?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template