You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改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_annot function: 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 names array, 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

  1. In the update_annot function:
    • 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 x and y arrays
    • Create a formatted string with those values (using \n to split X and Y onto separate lines for readability, and .4f to show 4 decimal places—you can adjust this precision to fit your needs)
  2. Removed the unused names array 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:40:08