获取Matplotlib单选按钮的状态

时间:2015-01-05 17:18:27

标签: python matplotlib scipy

使用Matplotlib,我可以使用“mySlider.val”获取Slider小部件的值,这非常方便。是否有相同的功能来获得当前选择的单选按钮?我认为这个问题是this question试图提出的问题,但提问者没有提供一个有效的例子。我提供了以下示例,指出我正在寻找的缺少的代码行。

from matplotlib.widgets import RadioButtons, Button, Slider
import matplotlib.pyplot as plt

axSlider = plt.axes([0.1, 0.8, 0.4, 0.05])
aSlider  = Slider(axSlider,'A slider', 0,1,  valinit=0.5)

axRadio  = plt.axes([0.1, 0.2, 0.3, 0.4])
butRadio = RadioButtons(axRadio, ('Top','Middle','Bottom'))

axStatus = plt.axes([0.5, 0.2, 0.3, 0.4])
bStatus  = Button(axStatus,'Get status of radio buttons')

def get_status(val):
    #radioValue = ???? -- Need this line of code.
    radioValue = 0
    sliderValue= aSlider.val
    print 'Slider value: %.2f, Radio button value: %.2f'%(sliderValue,radioValue)

bStatus.on_clicked(get_status)
plt.show()

以下是输出结果:

enter image description here

如果无法做到这一点,你能建议一个优雅的解决方案吗?目前我正在使用单选按钮的“on_clicked”功能,并使用单选按钮的值设置全局变量,这很麻烦。

3 个答案:

答案 0 :(得分:4)

正如@tcaswell所建议的,我在github上向matplotlib提交了一个pull request,现在可以查询RadioButtons的当前状态。缺少的代码行是:

radioValue = butRadio.value_selected

计划将其纳入matplotlib的1.5.x版本中。同时,如果要使用此功能,则需要下载matplotlib from github的开发版本(或至少下载'widgets.py'文件)。

现在已将其纳入当前版本的Matplotlib(1.5.3)。 (请参阅Widets Docs。)如果以上行不起作用,您可以更新Matplotlib。

答案 1 :(得分:1)

最简单的答案是:

from matplotlib.widgets import RadioButtons, Button, Slider
import matplotlib.pyplot as plt

axSlider = plt.axes([0.1, 0.8, 0.4, 0.05])
aSlider  = Slider(axSlider,'A slider', 0,1,  valinit=0.5)

axRadio  = plt.axes([0.1, 0.2, 0.3, 0.4])
my_list = ('Top','Middle','Bottom')
butRadio = RadioButtons(axRadio, my_list)

axStatus = plt.axes([0.5, 0.2, 0.3, 0.4])
bStatus  = Button(axStatus,'Get status of radio buttons')

def activated_radio_button(x,list):     
    for i in xrange(len(x.circles)):
                if x.circles[i].get_facecolor()[0]<.5:
                    return list[i]

def get_status(label):
    radioValue = activated_radio_button(butRadio,my_list)
    sliderValue= aSlider.val
    print 'Slider value: %.2f, Radio button value: %s'%(sliderValue,radioValue)

bStatus.on_clicked(get_status)
plt.show()

答案 2 :(得分:0)

Just stumbled across this post doing research on the same issue. They haven't made any update to matplotlib yet, though I did find a related post on retrieving the value from matplotlib's checkbuttons here: Retrieving the selected values from a CheckButtons object in matplotlib

To summarize the answer, is to keep a dict in which you store a variable for each button. Whenever the button is pressed, have the event handler change the necessary values in the dict, which could then be accessed by other functions as needed instead of the values being trapped within just the event handler.

Hope this helps! I know I'd rather not play around with matplotlib's source code