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

How to Add Hovering Annotations to Matplotlib Scatter Plots?

Barbara Streisand
Release: 2024-12-23 05:41:18
Original
986 people have browsed it

How to Add Hovering Annotations to Matplotlib Scatter Plots?

How to Create Hovering Annotations in a Plot

When analyzing scatter plots with numerous data points, identifying specific points of interest can be challenging. One convenient solution is to implement hovering annotations that display additional information upon cursor movement.

The matplotlib library provides a versatile functionality for adding annotations to plots. To create hovering annotations, we can utilize the annotate and update_annot functions. The annotate function positions an annotation at a specified coordinate, while update_annot modifies its text and appearance based on the index of the hovered data point.

To achieve hovering annotations, follow these steps:

  1. Import the required libraries and generate your data.
  2. Create a scatter plot and an invisible annotation object.
  3. Define the update_annot function to update the annotation's text and appearance based on the hovered point's index.
  4. Implement the hover function to control the annotation's visibility based on cursor movement.
  5. Connect the motion_notify_event to the hover function.

By implementing this approach, you can easily add hovering annotations to your scatter plots, providing valuable insights into specific data points without cluttering the plot.

Example:

The provided code snippet demonstrates the implementation of hovering annotations on a scatter plot:

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

x = np.random.rand(15)
y = np.random.rand(15)
names = np.array(list("ABCDEFGHIJKLMNO"))
c = np.random.randint(1,5,size=15)

norm = plt.Normalize(1,4)
cmap = plt.cm.RdYlGn

fig,ax = plt.subplots()
sc = plt.scatter(x,y,c=c, s=100, cmap=cmap, norm=norm)

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)

def update_annot(ind):

    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"]]))
    annot.set_text(text)
    annot.get_bbox_patch().set_facecolor(cmap(norm(c[ind["ind"][0]])))
    annot.get_bbox_patch().set_alpha(0.4)


def hover(event):
    vis = annot.get_visible()
    if event.inaxes == ax:
        cont, ind = sc.contains(event)
        if cont:
            update_annot(ind)
            annot.set_visible(True)
            fig.canvas.draw_idle()
        else:
            if vis:
                annot.set_visible(False)
                fig.canvas.draw_idle()

fig.canvas.mpl_connect("motion_notify_event", hover)

plt.show()
Copy after login

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

source:php.cn
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