Reputation:
I am trying to plot some data from a camera dynamically using drawnow. However, the dynamic plotting (using matplotlib and drawnow) doesn't seem to be working on jupyter notebook.
It's currently working in Pycharm.
My code:
import matplotlib.pyplot as plt
import numpy as np
from drawnow import *
x = np.random.randn(10, 2)
def function_to_draw_figure():
plt.plot(i, j, 'r.')
plt.ion()
figure()
for i, j in x:
drawnow(function_to_draw_figure)
plt.xlim(-1, 1)
plt.ylim(-1, 1)
plt.pause(0.5)
I would expect this example to plot 10 points dynamically on the same figure (as in pycharm). What actually happens is that multiple figures appear rather than one.
Any thoughts why I am not able to do it using jupyter notebook?
Upvotes: 0
Views: 2771
Reputation: 339300
I never quite understood the purpose of drawnow
. You should get the exact same result just calling your function.
Neither drawnow nor its equivalent simply using plt.ion()
and plt.draw()
or plt.pause()
will work in jupyter notebooks. For sure not using the %matplotlib inline
backend (because you cannot animate pngs); but also not with the %matplotlib notebook
backend due to the event loop which has not been started until the final figure is shown.
Options to show an animation in jupyter notebooks are listed in Animation in iPython notebook.
The recommended way would be to create a FuncAnimation
.
The animation from above would then look like
%matplotlib notebook
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
x = np.random.rand(10, 2)
def function_to_draw_figure(i):
line.set_data(*x[i,:])
plt.figure()
line, = plt.plot([], marker="o")
plt.xlim(0, 1)
plt.ylim(0, 1)
ani = FuncAnimation(plt.gcf(), function_to_draw_figure, frames=len(x),
interval=500, repeat=False)
plt.show()
Upvotes: 1
Reputation: 1782
Have you tried using matplotlib with the notebook
backend in your Jupyter notebook?
You can do this by adding %matplotlib notebook
magic command in a cell at the beginning of your notebook (e.g. right after importing matplotlib
)
More info here: http://ipython.readthedocs.io/en/stable/interactive/plotting.html
Upvotes: 0