gpt4 book ai didi

python - Matplotlib 错误发生在我第一次运行 Jupyter 单元格但不是第二次

转载 作者:太空宇宙 更新时间:2023-11-03 11:15:43 25 4
gpt4 key购买 nike

我第一次运行此代码块时出现错误,但之后没有。谁能帮我理解为什么?

根本没有关于此错误的先前 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'

最佳答案

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

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

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

关于python - Matplotlib 错误发生在我第一次运行 Jupyter 单元格但不是第二次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52055673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com