python - 按钮在轴中的定位 (matplotlib)

标签 python matplotlib

我有一个包含许多补丁的现有绘图(轴)。我希望向现有轴添加一些按钮。如果我编写以下代码,它将使整个轴作为按钮,即在轴上的任何位置检测到单击。

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

example matplotlib 给出的不使用现有轴,而是使用新轴(?)

# 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)

有没有办法可以将 Button 定位在现有轴上?

最佳答案

matplotlib.widgets.Button 位于其自己的轴中,​​您需要通过第一个参数提供该轴。所以你需要在某处创建一个轴。

根据您想要实现的目标,您可以简单地选择轴内的坐标,

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

这里的坐标以图形宽度和高度为单位。因此,按钮将创建为图形宽度的 40%、图形高度的 50%、宽度为 20%、高度为 7.5%。

enter image description here

或者,您可以使用 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()

此处,按钮位于轴宽度的 40%、高度的 50%、轴宽度的 20% 和高度的 8%。

enter image description here

关于python - 按钮在轴中的定位 (matplotlib),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47489873/

相关文章:

python - 该代码如何找到二叉树的最小深度?

python - Pandas 数据框作为 matplotlib.pyplot.boxplot 的输入

python - scipy.signal.cwt() 函数的 "widths"参数的单位

python - 使用 savefig 的 Matplotlib 多处理字体损坏

python - 如何对列表中的多个字符串进行反向互补

python - Telnet输出解析

python - 在一个图中叠加两个密度

python - 是否可以将 sphinx 预先生成的 html 文档上传到 ReadTheDocs 网站?

python - 如何使用 matplotlib 创建某种类型的网格

matplotlib - 为什么 Pandas 在不对称误差条的两侧应用相同的值?