是否可以通过不每次都生成新图形来加快交互式 IPython Notebook 绘图的速度?

Is it possible to speed up interactive IPython Notebook plots by not generating new figures every time?

我在笔记本中看到的使用小部件进行交互式 matplotlib 绘图的每个示例都是这样的(改编自 here):

%matplotlib inline

import numpy as np
import matplotlib.pyplot as plt
from IPython.html.widgets import interact
from IPython.display import display

def sigmoid_demo(a=5,b=1):
    x = np.linspace(0,10,256)
    s = 1/(1+np.exp(-(x-a)/(b+0.1))) # +0.1 to avoid dividing by 0
    sn = 100.0*(s-min(s))/(max(s)-min(s)) # normalize sigmoid to 0-100

    # Does this have to be in this function?
    fig, ax = plt.subplots(figsize=(24,6))

    ax.set_xticks([])
    ax.set_yticks([])
    plt.plot(x,sn,lw=2,color='black')
    plt.xlim(x.min(), x.max())

w=interact(sigmoid_demo,a=5,b=1)

我怀疑如果您不必在每次调整小部件时都使用 plt.subplots()plt.figure() 创建一个全新的图形,那么情节的响应速度可能会大大加快。

我尝试了一些方法来将图形创建移动到 interact() 调用的函数之外,但没有任何效果。

一些设置:

%matplotlib notebook
import matplotlib.pyplot as plt
from IPython.html.widgets import interactive
from IPython.display import display
import numpy as np

创建对象:

fig, ax = plt.subplots()
ax.set_xlim(0, .25)
ax.set_ylim(-2.5, 2.5)
ax.set_title('beat frequencies')
lnA, = ax.plot([], [], color='r', label='A')
lnB, = ax.plot([], [], color='purple', label='B')
lnsum, = ax.plot([], [], color='k', label='signal')
ax.legend()
max_time = 3
rate = 8000
times = np.linspace(0,max_time,rate*max_time)

def beat_freq(f1=220.0, f2=224.0):

    A = np.sin(2*np.pi*f1*times)
    B = np.sin(2*np.pi*f2*times)
    sig = A + B

    lnA.set_data(times, A)
    lnB.set_data(times, B)
    lnsum.set_data(times, sig)

    plt.draw()

beat_freq(0, 0)

和互动(我认为需要放在它自己的单元格中)

interactive(beat_freq, f1=(200.0,300.0), f2=(200.0,300.0))

您还可以戳其他单元格中的对象:

ax.set_xlim(0, .05)
ax.set_ylim(-2, 2)
plt.draw()

lnB.set_color('g')
ax.legend()
plt.draw()