Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib Button

Matplotlib Widget Buttons event and fig.canvas.mpl_connect('button_press_event') will both be triggered when mouse is clicked against the button.

My problem are :

1) how to make fig.canvas.mpl_connect('button_press_event') event have a higher priority ? and 2) how to tell within an fig.canvas.mpl_connect('button_press_event') event whether the button is being clicked or not.

import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons


fig = plt.figure()
# plotting
X=[1,2,3]
Y=[10,20,30]
ax  = fig.add_subplot(1, 1, 1)
ax.plot(X,Y,'bo-')
ax.grid()
ax.legend()
X1=[]
Y1=[]

def on_press(event):
    print "canvas clicked"
    print "how can I tell whether the button is clicked?"
    print event
def on_button_clicked(event):
    print "button clicked"
    print event
axnext = plt.axes([0.81, 0.05, 0.1, 0.075])
bnext = Button(axnext, 'Next')
bnext.on_clicked(on_button_clicked)
fig.canvas.mpl_connect('button_press_event', on_press)
plt.show()
like image 234
FreeToGo Avatar asked Jun 07 '26 17:06

FreeToGo


1 Answers

About the first point, why do you need that? Can you just ignore the event in that case?

Regarding the second point, you can use bnext.label.clipbox.get_points() to extract the coordinates of the button, and compare them with the coordinates of the mouse event, like in the example below:

import matplotlib.pylab as plt
from matplotlib.widgets import Button


fig,ax = plt.subplots()
ax.plot([1,2,3],[10,20,30],'bo-')
axnext = plt.axes([0.81, 0.05, 0.1, 0.075])
bnext = Button(axnext, 'Next')

(xm,ym),(xM,yM)=bnext.label.clipbox.get_points()

def on_press(event):

    if xm<event.x<xM and ym<event.y<yM:
        print "Button clicked, do nothing. This triggered event is useless."
    else:
        print "canvas clicked and Button not clicked. Do something with the canvas."
    print event
def on_button_clicked(event):
    print "button clicked, do something triggered by the button."
    print event

bnext.on_clicked(on_button_clicked)
fig.canvas.mpl_connect('button_press_event', on_press)
plt.show()
like image 85
gg349 Avatar answered Jun 10 '26 15:06

gg349



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!