Dynamic plot in python jupyter notebook using drawnow

早过忘川 提交于 2019-12-11 14:55:58

问题


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?


回答1:


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()



回答2:


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



来源:https://stackoverflow.com/questions/50103957/dynamic-plot-in-python-jupyter-notebook-using-drawnow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!