vyi
vyi

Reputation: 1092

Button positioning in axes (matplotlib)

I have an existing plot (axes) with many patches. And I wish to add a few Buttons to the existing axes. If I write the following code it makes the whole axes as the button i.e. click is detected everywhere on the axes.

# ax is the reference to axes containing many patches
bSend = Button(ax, 'send')
bSend.on_clicked(fu)

The example given by matplotlib does not use the existing axes but uses a new axes (?)

# Create axes
axprev = plt.axes([0.7, 0.05, 0.1, 0.075])
axnext = plt.axes([0.81, 0.05, 0.1, 0.075])

# Make Buttons of those axes.
bnext = Button(axnext, 'Next')
bnext.on_clicked(callback.next)
bprev = Button(axprev, 'Previous')
bprev.on_clicked(callback.prev)

Is there a way that I can position Button on the existing axes?

Upvotes: 6

Views: 4230

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339250

The matplotlib.widgets.Button lives in its own axes, which you need to supply via the first argument. So you need to create an axes somewhere.

Depending on what you are trying to achieve, you may simply choose coordinates inside the axes,

button_ax = plt.axes([0.4, 0.5, 0.2, 0.075])  #posx, posy, width, height
Button(button_ax, 'Click me')

The coordinates here are in units of the figure width and height. Hence the button will be created at 40% of figure width, 50% of figure height and is 20% wide, 7.5% heigh.

enter image description here

Alternatively you may place the button axes relative to the subplot axes using InsetPosition.

import matplotlib.pyplot as plt
from  matplotlib.widgets import Button
from mpl_toolkits.axes_grid1.inset_locator import InsetPosition

fig, ax= plt.subplots()

button_ax = plt.axes([0, 0, 1, 1])
ip = InsetPosition(ax, [0.4, 0.5, 0.2, 0.1]) #posx, posy, width, height
button_ax.set_axes_locator(ip)
Button(button_ax, 'Click me')

plt.show()

Here, the button is positioned at 40% of the axes width and 50% of its height, 20% of the axes width long, and 8% heigh.

enter image description here

Upvotes: 8

Related Questions