动态绘图适用于IDLE,但不适用于jupyter笔记本

时间:2017-04-27 16:46:40

标签: matplotlib jupyter-notebook python-3.6

以下代码在空闲(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笔记本时,我正在添加魔术命令

我被告知的

%matplotlib notebook应该用于动态情节。

(我尝试了%matplotlib inline,但最终得到的是静态图)

但是,我最终会遇到此错误

 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:`

1 个答案:

答案 0 :(得分:2)

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