Search code examples
pythonmatplotlibmatplotlib-widget

Reset CheckButtons to original values in matplotlib


I have a couple of sliders, a checkbox with two options that I set to False, and a reset button, as follows:

#Slider
slider_M = plt.axes(rectM, facecolor=axcolor)   
svalueM = Slider(slider_M, 'M', s_Mmin, s_Mmax, valinit=s_Minit, valfmt="%1.2f")
svalueM.on_changed(updateChart) 

#CheckBox
ShkBox = plt.axes(rectC,facecolor=axcolor)
CheckPar = CheckButtons(ShkBox, ('Strong', 'Weak'), (False, False)) 
CheckPar.on_clicked(updateChart)

#Reset Button
resetax = plt.axes(rectR, facecolor=axcolor)
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
button.on_clicked(resetplt)

In my reset routine I use the following to reset my slider and CheckButtons:

def resetplt(event)
    svalueM.reset()   #Reset Slider
    CheckPar.set_active(0)  # Reset Checkbox

The issue is with the above, CheckPar.set_active(0) toggles the value of the FIRST checkbox. What I want is to reset both checkboxes to the original value of "False".

This appears doable in Tkinter and Java but I am unable to implement with matplotlib. The matplotlib documentation says to use

set_active(self, index)

to Directly (de)activate a check button by index, where index is an index into the original label list.

Unfortunately, I do not know how to implement this and I am unable to find any examples of where someone did. Things I've tried include:

CheckPar.set_active(0)
CheckPar.set_active(("Strong","Weak"),(0, 0))
CheckPar.set_active([0],[1])

The last two options result in errors of the type

TypeError: set_active() takes 2 positional arguments but 3 were given

I am able to determine the status of the boxes using

status = CheckPar.get_status()

But I cannot reset them to their original value.

Any help would be appreciated.

Thanks


Solution

  • You have to know the state of the boxes in their original state, then iterate through the boxes, and switch their state only if the current state does not match the original one.

    See this test:

    def resetplt(event):
        for i, (state, orig) in enumerate(zip(CheckPar.get_status(), origState)):
            if not state == orig:
                CheckPar.set_active(i)  # switch state
    
    
    fig, (ax1, ax2) = plt.subplots(1, 2)
    
    # CheckBox
    origState = (False, True)
    ShkBox = plt.axes(ax1)
    CheckPar = CheckButtons(ShkBox, ('Strong', 'Weak'), origState)
    
    # Reset Button
    resetax = plt.axes(ax2)
    button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
    button.on_clicked(resetplt)
    
    plt.show()