使用 ipywidgets 更新图表:

Ale*_*ont 3 seaborn jupyter-notebook ipywidgets

我在 jupyter 笔记本上使用 seaborn,并且想要一个滑块来更新图表。我的代码如下:

from ipywidgets import interact, interactive, fixed, interact_manual
import numpy as np
import seaborn as sns
from IPython.display import clear_output

def f(var):
    print(var)
    clear_output(wait=True)
    sns.distplot(list(np.random.normal(1,var,1000)))

interact(f, var=10);
Run Code Online (Sandbox Code Playgroud)

问题:每次移动滑块时,图表都会重复。我该如何更新图表?

byo*_*ess 6

Seaborn 图应像常规 matplotlib 图一样处理。因此,您需要使用此答案plt.show()中的解释来显示它。

%matplotlib inlinemagic 命令相结合,这对我来说效果很好:

%matplotlib inline
from ipywidgets import interact
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

def f(var):
    sns.distplot(np.random.normal(1, var, 1000))
    plt.show()
interact(f, var = (1,10))
Run Code Online (Sandbox Code Playgroud)

另一种解决方案是更新绘图的数据,而不是重新绘制新的数据,如下所述:https ://stackoverflow.com/a/4098938/2699660