The code below works fine when running through idle (Python 3.6 idle)
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()
When transferring this code to jupyter notebook, I'm adding the magic command
%matplotlib notebook
which I'm told should be used for dynamic plots.
(I tried %matplotlib inline, but I end up with a static plot)
However, I'm ending up with this error
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()
doesn't work with the %matplotlib notebook
, it's meant to be used in interactive mode, just as you used it in IDLE.
To overcome this there is an animation submodule which can be used.
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()
For more examples refer to the matplotlib page.
来源:https://stackoverflow.com/questions/43663613/dynamic-plot-works-in-idle-but-not-jupyter-notebook