sergiuspro
sergiuspro

Reputation: 121

Matplotlib: how to call a pick_event only upon a left-click button_press_event?

I have a simple interactive plot with a button_press_event and a pick_event handler:

    fig, ax1 = plt.subplots()
    line, = ax1.plot(x, y, picker=10)

    def pick_handler(event):
        print "Pick_handler called!"
        if isinstance(event.artist, Line2D):
            # do something

    def click_handler(event):
        if event.button == 1:
            print "Click_handler called by left-click!"
            fig.canvas.mpl_connect('pick_event', pick_handler)
        if event.button == 3:
            print "Click_handler called by right-click!"
            # do something

    fig.canvas.mpl_connect('button_press_event', click_handler)
    plt.show()

The desired behaviour is the following: only if I do a left-click in the plot, the pick_handler() should be called.

The given code behaves not as desired, there are several strange things happening.

1) When the plot appears and I do the first left-click anywhere in the plot, the click_handler() is called and print "Click_handler called by left-click!" is executed, but the pick_handler() is not called; only beginning with the second left-click the pick_handler() is called.

2) When I do the second and any further left-click anywhere in the plot, the click_handler() first calls the pick_handler() and only after that print "Click_handler called by left-click!" is executed, but according to the code it should be vice versa.

3) When the plot appears and my very first click is a right-click anywhere in the plot (aynwhere means even if I right-click some Line2D object), the code acts correctly – it just calls the click_handler() and executes print "Click_handler called by right-click!". But if my very first click is a left-click anywhere in the plot, and the second click is a right-click on some Line2D object in the plot, then the code calls the click_handler(), the click_handler() first calls and fully executes the pick_handler() and then executes print "Click_handler called by right-click!", but according to the code the pick_handler() should never be called by any right-click.

Is my code wrong or is my understanding of click- and pick-handlers wrong?

Upvotes: 2

Views: 1408

Answers (1)

Diziet Asahi
Diziet Asahi

Reputation: 40667

I think the following code is doing what you wanted:

fig, ax1 = plt.subplots()
line, = ax1.plot(x, y, 'o', picker=10)

def pick_handler(event):
    print("Pick_handler called!")
    if event.mouseevent.button==1 and isinstance(event.artist, Line2D):
        print("Do the thing.")

def click_handler(event):
    if event.button == 3:
        print("Click_handler called by right-click!")
        # do something

fig.canvas.mpl_connect('pick_event', pick_handler)
fig.canvas.mpl_connect('button_press_event', click_handler)
plt.show()

Upvotes: 3

Related Questions