python-3.xmatplotlibmplcursors

How to highlight selected line in a multiple axes figure using matplotlib


I am trying to come up a code to highlight a selected line (by click or mouse hover) into a red line.

I've tried some solution that I found in how to highlight line collection in matplotlib, Changing marker colour on selection in matplotlib, https://github.com/joferkington/mpldatacursor, https://mplcursors.readthedocs.io/en/stable/

But most of the cases work on the single axes or two axes in one subplot. In my case, I need to work with multiple lines in multiple subplots.

I've tried:

def on_pick (event, fig, axes):
    for ax in axes:
        for line in ax.lines:
            if event.artist is line:
                ind = event.ind[0]
                line.set_color('red')
                fig.canvas.draw_idle()

fig1.canvas.mpl_connect('pick_event', lambda event: on_pick(event,fig1, axes))

When I clicked on my figure, nothing happened. So, I don't know how to achieve it.

To make a similar function work, showing the label of a selected line. I simply used:

import mplcursors

mplcursors.cursor().connect("add", lambda sel: sel.annotation.set_text(sel.artist.get_label()))

I wonder if I can use the same library or similar achieve my goal to highlight a selected line in given axes/subplot.

Below is my figure example (multiple axes and multiple lines) and code:

x1 = np.linspace(0, 10, num=6, endpoint=True)
y11 = abs(x1**2)
y12 = abs(x1/2)

x2 = np.linspace(1, 100, num=10, endpoint=True)
y21 = abs(x2/10)
y22 = abs(np.sqrt(x2))

x3 = np.linspace(50, 100, num=20, endpoint=True)
y31 = abs(x3**2)
y32 = abs(x3/5)


fig, axes = plt.subplots(3,1)

axes = axes.reshape(-1)

ax1 = axes[0]
ax2 = axes[1]
ax3 = axes[2]

ax1.plot(x1, y11, y12, picker = True)
ax2.plot(x2, y21, y22, picker = True)
ax3.plot(x3, y31, y32, picker = True)

def on_pick (event, fig, axes):
    for ax in axes:
        for line in ax.lines:
            if event.artist is line:
                ind = event.ind[0]
                line.set_color('red')
                fig.canvas.draw_idle()

fig.canvas.mpl_connect('pick_event', lambda event: on_pick(event,fig, axes))

However, the highlighted curve cannot recover to the original color once I pick the other line.

enter image description here

enter image description here

Note that this is a simplified example from my case.


Solution

  • import mplcursors
    
    mplcursors.cursor(highlight=True).connect("add", lambda sel: sel.annotation.set_text(sel.artist.get_label()))
    

    One line solved all problem!