Matplotlib error occurs first time I run Jupyter cell but not second time

Viewed 1516

The first time, but not subsequent times, I run this code block I get an error. Can anyone help me understand why please?

There are no previous SO posts on this error at all (at least in search results)

I am fairly new to coding. As far as I can tell it is a sequence error in my code. Namely, the first time the attribute isn't loaded (yet), then the attribute gets loaded further down the code block, making it available when I run the code again. Problem is I can't work out what part of the code it is.

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()

Error Message

> 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 Answers

Apparently the order of importing matplotlib.pyplot and setting the notebook backend matters.

When putting the %matplotlib notebook line on top, it works fine for me

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