1

I have an ipywidget that generates a plot each time the selection changes. Currently the plots are appended to each other; however, I would like to have only one plot (the latest).

import ipywidgets as widgets 
import matplotlib.pyplot as plt
def f(change):
    if change['type'] == 'change' and change['name'] == 'value':
        plt.close('all')  # seems to have no effect
        plt.plot([0, 1],[0, 10])
        plt.title(change['new'])
        plt.show()

w = widgets.Select(options=[0, 1])
w.observe(f)
display(w)

I tried without success:

Note: I'm not using interactive since I do not want to run all functions when any parameter changes.

Qaswed
  • 3,649
  • 7
  • 27
  • 47

1 Answers1

2

Try sending your charts to an Output widget, which can be used as a context manager, and then cleared with out.clear_output().

import ipywidgets as widgets 
import matplotlib.pyplot as plt
%matplotlib inline
out = widgets.Output(layout = widgets.Layout(height='300px'))

def f(change):
    if change['type'] == 'change' and change['name'] == 'value':
        with out:
            plt.plot([0, 1],[0, 10])
            plt.title(change['new'])
            out.clear_output()
            plt.show()

w = widgets.Select(options=[0, 1])
w.observe(f)
display(w)
display(out)
ac24
  • 5,325
  • 1
  • 16
  • 31
  • Adapted this code to add a comment to https://github.com/jupyter-widgets/ipywidgets/issues/1919#issuecomment-709917932 – astrojuanlu Oct 16 '20 at 08:53