TypeError: cannot unpack non-iterable Annotation object

I’m trying to associate lines with annotation with a label and I’m getting a “TypeError: cannot unpack non-iterable Annotation object” error. I’m rather new at python and I’m looking for a solution. The ultimate code would highlight the annotation and associated line when clicking either feature using mplcursors.

Below is a scaled down version of the code:

import numpy as np
import matplotlib.pyplot as plt
import mplcursors
def main():
    fig, axes = plt.subplots()
    lines = []
    texts = []
    for i in range(5):
        llabel='line '+str(i)
        line, = axes.plot((i + 1) * np.arange(10),label=llabel)
        lines.append(line)
    for i in range(5):
        llabel='line '+str(i)
        Last_y=(i + 1) * np.arange(10)
        text, =axes.annotate(' '+llabel, xy=(9.00,Last_y[-1]), xytext=(3,0), color='black', 
             textcoords="offset points",
            size=10, va="center" ,zorder=40,label=llabel )
        texts.append(text)
    plt.show()
if __name__ == "__main__":
    main()

a, = function() is short hand for "just give me the first thing that function returns. But if function only returns one thing, the unpacking will fail and you will get that error.

Above you need the unpacking for plot because it returns a few things, but axes.annotate only returns one thing.

Thanks for that reply. Here is a link to what I would like to accomplish: Linked artists — mplcursors 0.4 documentation
but in my case I want to link the annotation text instead of the points to the lines on a single plot. Can you give me any suggestions how this could work with matplotlib or should I give up.

It looks like you are on the right path. The issue is that ax.plot returns a length 1 list (which we implicitly unpack as line, = [line_obj] where is axes.annotate returns a single object. The exception you are getting is when you ask Python to unpack something that does not look like an iterable (ex a, = 1 will fail for the same reasion).

I think if you write

    text = axes.annotate(' '+llabel, xy=(9.00,Last_y[-1]), xytext=(3,0), color='black', 
             t           extcoords="offset points",
                         size=10, va="center" ,zorder=40,label=llabel )

(note the lack of ,) it will work as expected.