使用ipywidgets的交互式matplotlib

时间:2016-10-19 05:25:49

标签: python matplotlib ipython jupyter-notebook ipywidgets

我想在IPython(python3)中使用 Matplotlib ipywidgets 实现交互式情节。那么,我如何才能有效地做到这一点(顺利改变,没有延迟)?

另一个问题是为什么这段代码有效?!

from ipywidgets import *
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

x = np.linspace(0, 2 * np.pi)

def update(w = 1.0):
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(x, np.sin(w * x))

    fig.canvas.draw()

interact(update);

enter image description here

但是,这不起作用?!

from ipywidgets import *
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

x = np.linspace(0, 2 * np.pi)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
line, = ax.plot(x, np.sin(x))

def update(w = 1.0):
    line.set_ydata(np.sin(w * x))
    fig.canvas.draw()

interact(update);

enter image description here

1 个答案:

答案 0 :(得分:3)

第二种方法是笔记本后端的正确方法

%matplotlib notebook

或者使用ipympl。

然而,它不能使用内联后端,而后端不会更新情节。