Home > Software engineering >  how to manage event handling in matlpotlib with multiple plots in python?
how to manage event handling in matlpotlib with multiple plots in python?

Time:10-02

I want to know when I click on a plot, which one is it of all mi graphs . This function correctly returns the xdata and ydata, but it does not tell me which graph I clicked on. I have a code similar to this function "onclick":

fig, ax = plt.subplots()
ax.plot(np.random.rand(10))

def onclick(event):
    print('%s click: button=%d, x=%d, y=%d, xdata=%f, ydata=%f' %
          ('double' if event.dblclick else 'single', event.button,
           event.x, event.y, event.xdata, event.ydata))

cid = fig.canvas.mpl_connect('button_press_event', onclick)

CodePudding user response:

From the documentation here, it looks like you can get that information by using:

fig.canvas.mpl_connect('axes_enter_event', enter_axes)
fig.canvas.mpl_connect('axes_leave_event', leave_axes)

With:

def enter_axes(event):
    print('enter_axes', event.inaxes)
    event.inaxes.patch.set_facecolor('yellow')
    event.canvas.draw()

and

def leave_axes(event):
    print('leave_axes', event.inaxes)
    event.inaxes.patch.set_facecolor('white')
    event.canvas.draw()

You can recognize the subplots from event.inaxes

  • Related