How to Add Hovering Annotations to a Plot
Annotating points on a scatter plot is a common task when working with data. Matplotlib, a Python library for creating 2D plots, provides a simple method for adding fixed annotations to a plot using the annotate command. However, this approach can become impractical when dealing with numerous data points as the plot might become cluttered.
Fortunately, there is a solution that involves creating dynamic annotations that only appear when the cursor hovers over a specific data point. This method requires a slight modification of the annotate function in conjunction with a callback function to handle cursor events.
Here's an example code demonstrating the implementation:
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()
This code adds a toolTip that appears when the mouse hovers over a data point, displaying its coordinates and name. The update_annot function dynamically updates the annotation's position and content depending on the hovered point.
This approach allows for a clutter-free visualization with easily accessible information about each data point, making it suitable for interactive data exploration.
The above is the detailed content of How to Create Hovering Annotations for Scatter Plots in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!