Matplotlib错误在我第一次运行Jupyter单元时发生,但第二次没有发生

时间:2018-08-28 10:27:43

标签: python matplotlib runtime-error

第一次但不是以后,我运行此代码块时遇到错误。有人可以帮我理解为什么吗?

以前根本没有关于此错误的SO帖子(至少在搜索结果中如此)

我是编码的新手。据我所知,这是我的代码中的顺序错误。即,第一次(尚未)加载该属性时,然后将该属性加载到代码块的更下方,使它在我再次运行代码时可用。问题是我无法确定代码的哪一部分。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

%matplotlib notebook

def data_gen(t=0):
    cnt = 0
    while cnt < 150:
        cnt += 1
        t += 0.1
        yield t, np.sin(2*np.pi*t) * np.exp(-t/10.)


def init():
    ax.set_ylim(-1.1, 1.1)
    ax.set_xlim(0, 10)
    del xdata[:]
    del ydata[:]
    line.set_data(xdata, ydata)
    return line,

fig, ax = plt.subplots()
line, = ax.plot([], [], lw=2)
ax.grid()
xdata, ydata = [], []


def run(data):
    # update the data
    t, y = data
    xdata.append(t)
    ydata.append(y)
    xmin, xmax = ax.get_xlim()

    if t >= xmax:
        ax.set_xlim(xmin, 2*xmax)
        ax.figure.canvas.draw()
    line.set_data(xdata, ydata)

    return line,

ani = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=15,
                              repeat=False, init_func=init)                                   

plt.show()

错误消息

> Traceback (most recent call last):   File
> "/Users/alexfreeman/Documents/Dev/AnacondaInstall/anaconda/envs/py3-env/lib/python3.6/site-packages/matplotlib/cbook/__init__.py",
> line 387, in process
>     proxy(*args, **kwargs)   File "/Users/alexfreeman/Documents/Dev/AnacondaInstall/anaconda/envs/py3-env/lib/python3.6/site-packages/matplotlib/cbook/__init__.py",
> line 227, in __call__
>     return mtd(*args, **kwargs)   File "/Users/alexfreeman/Documents/Dev/AnacondaInstall/anaconda/envs/py3-env/lib/python3.6/site-packages/matplotlib/animation.py",
> line 1499, in _stop
>     self.event_source.remove_callback(self._loop_delay) AttributeError: 'NoneType' object has no attribute 'remove_callback'

1 个答案:

答案 0 :(得分:1)

显然,导入matplotlib.pyplot和设置notebook后端的顺序很重要。

%matplotlib notebook行放在顶部时,对我来说很好

%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation