How to clear a Matplotlib subplot canvas figure when a new radio button is clicked PySimpleGUI?

1.3k views Asked by At

I have a GUI with multiple radio buttons. Each time I change a button - I want to create a new graph for which I have created a function. My issue is that when I click another radio button, the first graph and second graph show. I would like to clear the first graph so only the second graph shows when the relevant button is clicked. Please could someone help create a function for this?

My function below gives me an error.



def draw_figure(canvas, figure):
    figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
    figure_canvas_agg.draw()
    figure_canvas_agg.get_tk_widget().pack(side='top', fill='both', expand=1)
    return figure_canvas_agg

def delete_figure_agg(figure_agg):
    figure_agg.get_tk_widget().forget()
    plt.close('all') 
 
 layout=[          
[sg.Radio('1',key= 'RADIO1',group_id='1', enable_events = True,default=False, size=(10,1)),
          sg.Radio('2t', key= 'RADIO2',group_id='1',enable_events = True, default=False, size=(10,1)),
           sg.Radio('3', key='RADIO3',group_id='1',enable_events = True, default=False, size=(12,1)),
           sg.Radio('4', key='RADIO4', group_id='1',enable_events = True,default=False, size=(12,1))],
           [sg.Canvas(key='-CANVAS-',size=(40,40))]]

def subplot_graph(val1, val2,val3, val4):
    fig = matplotlib.figure.Figure(figsize=(4, 4), dpi=75)
    fig.add_subplot(111).bar(val1, val2,color= 'blue' ,width=0.7)
    fig.add_subplot(111).twinx()
    fig.add_subplot(111).plot(val1,val3))
    return fig

Thank you

1

There are 1 answers

1
Mike from PSG On BEST ANSWER

An example of doing this is in the Demo_Matplotlib_Browser. This demo shows multiple plots, one after another, which is your clue to check there to see how it's done by that code.

The technique used in that demo is this function:

def delete_figure_agg(figure_agg):
    figure_agg.get_tk_widget().forget()
    plt.close('all')