在 matplotlib 中将鼠标悬停在垂直跨越区域上时显示标签
show label on hover over vertically spanned area in matplotlib
当我将鼠标悬停在跨越区域上时,标签只显示在跨越区域的两侧,而不是整个区域。
我希望当鼠标悬停在标签上时,整个区域都能看到标签。我该如何实现这个逻辑?
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()
我不知道为什么 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()
当我将鼠标悬停在跨越区域上时,标签只显示在跨越区域的两侧,而不是整个区域。
我希望当鼠标悬停在标签上时,整个区域都能看到标签。我该如何实现这个逻辑?
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()
我不知道为什么 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()