Different Callback for each subplot using subplot2grid

209 views Asked by At

Hello dear Python comunity developper, I would like to know if there is a way to have different callback for every subplot2grid (matplotlib), For example: For the first subplot2grid I want to execute a function which is different from the second subplot2grid that generates executes another function.

I specify that i'm using subplot2grid and not subplot in matplotlib. Thank you,

1

There are 1 answers

3
Diziet Asahi On BEST ANSWER

If your goal is to use a widget.Button for each subplot, then the situation is very easy. To create a button you need to pass it an Axes instance and the button will occupy that space. So you need to create as many new axes as you have subplots, and specify their coordinates appropriately. Then create your buttons, which can have different callback functions.

for example:

from matplotlib.widgets import Button

def callback1(event):
    print "you've clicked button 1"

def callback2(event):
    print "you've clicked button 2"

fig = plt.figure()
ax1 = plt.subplot2grid((2,2),(0, 0))
ax2 = plt.subplot2grid((2,2),(1,1))

# create axes to receive the buttons
# adjust the coordinates to suit your needs
# coordinates are [left, bottom, width, height]
b1ax = plt.axes([0.5, 0.8, 0.2, 0.1])
b1 = Button(b1ax, 'Button 1')
b1.on_clicked(callback1)
b2ax = plt.axes([0.7, 0.5, 0.2, 0.1])
b2 = Button(b2ax, 'Button 2')
b2.on_clicked(callback2)
plt.show()

enter image description here

documentation for widget.Button: http://matplotlib.org/api/widgets_api.html#matplotlib.widgets.Button

example of implementation: http://matplotlib.org/examples/widgets/buttons.html