使用drawow的python jupyter笔记本中的动态图

Dynamic plot in python jupyter notebook using drawnow

我正在尝试使用drawow动态绘制摄像机的一些数据。但是,动态绘图(使用matplotlib和Drawnow)似乎在jupyter笔记本上不起作用。

它正在Pycharm中运行。

我的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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)

我希望本示例在同一图上动态绘制10个点(如pycharm中所示)。实际发生的是出现多个数字而不是一个。

有人想过为什么我无法使用jupyter笔记本来做到这一点吗?


我从不完全了解drawnow的目的。只需调用函数,您应该得到完全相同的结果。

drawow或仅使用plt.ion()plt.draw()plt.pause()的等效项在jupyter笔记本中均不起作用。确保不使用%matplotlib inline后端(因为您无法为png设置动画);但由于事件循环直到显示最终图形才开始,因此还没有%matplotlib notebook后端。

在jupyter笔记本中显示动画的选项列在
iPython笔记本中的动画。

建议的方法是创建FuncAnimation

上方的动画如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
%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()


您是否尝试过在Jupyter笔记本中将matplotlib与notebook后端一起使用?

您可以通过在笔记本开头的单元格中添加%matplotlib notebook magic命令来执行此操作(例如,在导入matplotlib之后立即添加)

此处提供更多信息:http://ipython.readthedocs.io/en/stable/interactive/plotting.html