2017-11-25 220 views
1

我有一個有許多補丁的現有圖(軸)。我想添加幾個按鈕到現有的軸。如果我編寫下面的代碼,它會將整個軸作爲按鈕,即在軸上的任何地方檢測到單擊。座標軸中的按鈕(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) 

有沒有一種方法,我可以在現有軸位置按鈕?

回答

2

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

+0

謝謝你這樣詳細的答案!我認爲可能有一種方法可以將按鈕添加到**現有的座標軸**,並且不會這樣,我將使用「每個按鈕1軸」的方式。謝謝。 – vvy

+0

想想它更像是Button **是**軸。你有一個座標軸可以繪製到另一個座標軸,**是按鈕。所以你要做的是將一個現有的軸轉換成一個Button。 – ImportanceOfBeingErnest

+0

當然。在第二個解析中,我看到你已經使用了'InsetPosition',我喜歡這個。謝謝。 – vvy