when I hover over spanned region, labels are being showed only along the sides of spanned area but not through out the area.
I want the label to be viewed in the whole area when I hover in it. How can I implement this logic?
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()
I don't know why mplcursors
does not work in the code from the question; but here is how to show an annotation upon hovering an axes span (without 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()