3

当我将鼠标悬停在跨越区域上时,标签仅显示在跨越区域的两侧,而不是整个区域。

当我将鼠标悬停在标签上时,我希望在整个区域中查看标签。我该如何实现这个逻辑?

import matplotlib.pyplot as plt
import mplcursors


plt.axvspan(2,3,gid='yes',alpha=0.3,label = 'y')


mplcursors.cursor(hover=True).connect(
      "add", lambda sel: sel.annotation.set_text(sel.artist.get_label()))


plt.show()
4

1 回答 1

3

我不知道为什么mplcursors在问题的代码中不起作用;但这里是如何在悬停轴跨度时显示注释(没有 mplcursors):

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
span = ax.axvspan(2,3,gid='yes',alpha=0.3,label = 'y')

annot = ax.annotate("Y", xy=(0,0), xytext=(20,20), textcoords="offset points",
                    bbox=dict(boxstyle="round", fc="w"),
                    arrowprops=dict(arrowstyle="->"))
annot.set_visible(False)

def hover(event):
    vis = annot.get_visible()
    if event.inaxes == ax:
        cont, ind = span.contains(event)
        if cont:
            annot.xy = (event.xdata, event.ydata)
            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()
于 2019-12-20T15:02:37.400 回答