anntzer / mplcursors

Interactive data selection cursors for Matplotlib.
https://mplcursors.readthedocs.io
zlib License
114 stars 20 forks source link

Restrict annotation to one figure when multiple figures are open #52

Closed talcat closed 2 years ago

talcat commented 2 years ago

I noticed that when I have multiple figures open to compare data, whenever I draw a figure with annotation on hover attached, all previous figures suddenly also have annotation-on-hover, and then python spits out warnings because I never defined what should be shown in annotations on previous plots.

I thought this stackoverflow would solve my problem (I think the keyword is just 'artists' now?), but it doesn't seem to like taking a list of axes.

Is there any way to attach a cursor to a specific figure, and not have it retroactively attach to all previously open figures?

I'm working in a jupyter notebook with the qt backend.

Working example: first cell:

fig1, bx1 = plt.subplots()
bx1.plot([12, 13, 14, 15], [1, 2, 3, 4], '.')

Second cell:

fig, axs = plt.subplots(ncols=2, sharey=False)

axs[0].plot([1, 2, 3, 4, 5], [6, 7, 8, 9, 10], '.', label='Test1')
axs[1].plot([6, 7, 8, 9, 10], [1, 2, 3, 4,5 ], '.', label='Test1')

#on hover, show seq id
cursor = mplcursors.cursor( hover=mplcursors.HoverMode.Transient)
@cursor.connect('add')
def on_add(sel):
    sel.annotation.set_text((sel.artist.get_label()))
mplcursors.cursor().connect("add", lambda sel: sel.annotation.set_text(sel.artist.get_label()))

Once the second cell is run, annotations suddenly work on the first figure.

Edit: Also, if you try to explicitly list just the lines you want (such as passing fig.findobject(matplotlib.lines.Line2D) to artists), it returns a type error: TypeError: __init__() got multiple values for argument 'artists'

But the documentation says artists can take a list of Artist objects?

Thanks again

anntzer commented 2 years ago

The kwarg is called pickables now (as noted in https://mplcursors.readthedocs.io/en/stable/mplcursors.html#mplcursors.cursor). Also, passing a list of Axes should also work?

talcat commented 2 years ago

Thanks so much! I really don't know how I missed that in the docs....

Sorry about that