清除 ipywidgets.observe 生成的图

Clear plots generated by ipywidgets.observe

我有一个 ipywidget,每次选择更改时都会生成一个图。目前这些地块是相互附加的;但是,我只想 one 情节(最新)。

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)

我试过没有成功:

注意:我没有使用 interactive,因为 I do not want to run all functions when any parameter changes

尝试将您的图表发送到 Output 小部件,它可以用作上下文管理器,然后使用 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)