简体   繁体   中英

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 ie 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 ?

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.

在此处输入图片说明

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.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM