gpt4 book ai didi

matplotlib - 动态绘图适用于 IDLE,但不适用于 jupyter notebook

转载 作者:行者123 更新时间:2023-12-05 04:10:55 31 4
gpt4 key购买 nike

下面的代码在空闲时运行正常(Python 3.6 空闲)

import matplotlib.pyplot as plt
import time
import random
#%matplotlib inline

ysample = random.sample(range(-50, 50), 100)

xdata = []
ydata = []

plt.show()

axes = plt.gca()
axes.set_xlim(0, 100)
axes.set_ylim(-50, +50)
line, = axes.plot(xdata, ydata, 'r-')

for i in range(100):
xdata.append(i)
ydata.append(ysample[i])
line.set_xdata(xdata)
line.set_ydata(ydata)
plt.draw()
plt.pause(1e-17)
time.sleep(0.1)

# add this if you don't want the window to disappear at the end
plt.show()

将此代码传输到 jupyter notebook 时,我添加了魔术命令

%matplotlib notebook 我被告知应该用于动态绘图。

(我试过内联 %matplotlib,但我得到的是静态图)

但是,我最终遇到了这个错误

 NotImplementedError                       Traceback (most recent call last)
<ipython-input-7-2f88f762e22a> in <module>()
22 line.set_ydata(ydata)
23 plt.draw()
---> 24 plt.pause(1e-17)
25 time.sleep(0.1)
26

C:\Users\Moondra\AppData\Local\Programs\Python\Python36\lib\site-
packages\matplotlib\pyplot.py in pause(interval)
298 canvas.draw()
299 show(block=False)
--> 300 canvas.start_event_loop(interval)
301 return
302

C:\Users\Moondra\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\backends\backend_nbagg.py in start_event_loop(self, timeout)
192
193 def start_event_loop(self, timeout):
--> 194 FigureCanvasBase.start_event_loop_default(self, timeout)
195
196 def stop_event_loop(self):

C:\Users\Moondra\AppData\Local\Programs\Python\Python36\lib\site-
packages\matplotlib\backend_bases.py in start_event_loop_default(self, timeout)
2451 self._looping = True
2452 while self._looping and counter * timestep < timeout:
-> 2453 self.flush_events()
2454 time.sleep(timestep)
2455 counter += 1

C:\Users\Moondra\AppData\Local\Programs\Python\Python36\lib\site-
packages\matplotlib\backend_bases.py in flush_events(self)
2400 backends with GUIs.
2401 """
-> 2402 raise NotImplementedError
2403
2404 def start_event_loop(self, timeout):

NotImplementedError:`

最佳答案

plt.draw() 不适用于 %matplotlib notebook,它旨在用于交互模式,就像您在 IDLE 中使用它一样。

为了克服这个问题,有一个 animation submodule可以使用。

import matplotlib.pyplot as plt
import matplotlib.animation
import time
import random
%matplotlib notebook

ysample = random.sample(range(-50, 50), 100)

xdata = []
ydata = []

axes = plt.gca()
axes.set_xlim(0, 100)
axes.set_ylim(-50, +50)
line, = axes.plot(xdata, ydata, 'r-')

def update(i):
xdata.append(i)
ydata.append(ysample[i])
line.set_xdata(xdata)
line.set_ydata(ydata)

ani= matplotlib.animation.FuncAnimation(plt.gcf(), update, frames=100,
interval=100, repeat=False)

plt.show()

有关更多示例,请参阅 matplotlib page .

关于matplotlib - 动态绘图适用于 IDLE,但不适用于 jupyter notebook,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43663613/

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