Search code examples
pythonmatplotlibmplcursors

How can I show element's index number from a given list on hover in matplotlib graph in python?


I am using mplcursors module to show label value. I also want to show the index number from given lists for that particular point on which I will hover. My Example Code snippet:

import matplotlib.pyplot as plt
import mplcursors
lines = plt.plot([1, 2, 3, 4], [2, 4, 6, 10])
plt.ylabel('some numbers')
mplcursors.cursor(hover=True)
plt.show()

Is there any way that I can use the mplcursors to annotate the required information(as its easy)? Thanks :)


Solution

  • mplcursors allows to specify a function that is called every time just before an annotation is shown. That function gets a parameter sel which among others has a target field. In case of a "line", apart from the xy value, the target contains an index. The integer part of the index is an index into the x and y arrays of the left end of the segment the cursor is on. The fractional part of the index tells how far we are between the left and the right end of the segment.

    import matplotlib.pyplot as plt
    import mplcursors
    
    def show_annotation(sel):
        ind = int(sel.target.index)
        frac = sel.target.index - ind
        x, y = sel.target
        sel.annotation.set_text(f'left index:{ind} frac:{frac:.2f}\nx:{x:.2f} y:{y:.2f}')
    
    lines = plt.plot([1, 2, 3, 4], [2, 4, 6, 10])
    plt.ylabel('some numbers')
    cursor = mplcursors.cursor(hover=True)
    cursor.connect("add", show_annotation)
    plt.show()
    

    example annotation