如何修改Matplotlib代码实现折线图悬停显示真实X、Y值?
Fixing Matplotlib Hover Annotation to Show X/Y Values
No problem at all—let's adjust that hover text to display the actual X and Y values of the data points instead of indices and names. Here's exactly what you need to change:
Key Modifications
- Update the
update_annotfunction: The core fix is replacing the text generation logic that used indices and names with code that grabs the corresponding X and Y values from your data arrays. - Optional cleanup: Since we're no longer using the
namesarray, you can safely delete that line to keep the code tidy.
Modified Full Code
import matplotlib.pyplot as plt import numpy as np; np.random.seed(1) # Generate sample data x = np.sort(np.random.rand(15)) y = np.sort(np.random.rand(15)) fig, ax = plt.subplots() line, = plt.plot(x, y, marker="o") # Set up annotation box 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): # Get the index of the hovered data point point_index = ind["ind"][0] # Fetch the matching X and Y values from our data arrays hover_x = x[point_index] hover_y = y[point_index] # Format the text to show clean, readable X/Y values (adjust .4f for precision) text = f"X: {hover_x:.4f}\nY: {hover_y:.4f}" # Update annotation position and content annot.xy = (hover_x, hover_y) annot.set_text(text) annot.get_bbox_patch().set_alpha(0.4) def hover(event): vis = annot.get_visible() if event.inaxes == ax: cont, ind = line.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()
Breakdown of Changes
- In the
update_annotfunction:- We first pull the index of the hovered point from
ind["ind"][0] - Use that index to get the exact X and Y values from your original
xandyarrays - Create a formatted string with those values (using
\nto split X and Y onto separate lines for readability, and.4fto show 4 decimal places—you can adjust this precision to fit your needs)
- We first pull the index of the hovered point from
- Removed the unused
namesarray since it's no longer needed for the hover text
Now when you hover over any data point, the annotation will display the precise X and Y values instead of indices and letters.
内容的提问来源于stack exchange,提问作者shubham bansal
相关产品推荐
相关产品推荐

