【问题标题】:show label on hover over vertically spanned area in matplotlib在 matplotlib 中的垂直跨越区域上悬停时显示标签
【发布时间】:2019-12-20 11:42:09
【问题描述】:

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

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

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()

【问题讨论】:

    标签: python-3.x matplotlib plot mplcursors


    【解决方案1】:

    我不知道为什么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()
    

    【讨论】:

    • 感谢您提供上面的代码。但是如果我在图中有 n 个跨度,这是否意味着我也需要有 n 个注释?当我悬停时,不能直接显示艺术家标签而不是在注释中写标签然后显示它吗?
    • 不,您需要一个注释。您可以移动它并根据它的位置更改它的文本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多