【问题标题】:Dynamic plot in python jupyter notebook using drawnowpython jupyter notebook中使用drawow的动态绘图
【发布时间】:2018-05-01 01:24:53
【问题描述】:

我正在尝试使用drawow动态绘制来自相机的一些数据。但是,动态绘图(使用 matplotlib 和 drawow)似乎不适用于 jupyter notebook。

目前在 Pycharm 中运行。

我的代码:

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 notebook 做到这一点?

【问题讨论】:

    标签: python python-3.x matplotlib jupyter-notebook


    【解决方案1】:

    我一直不太明白drawnow 的用途。只需调用您的函数,您就应该得到完全相同的结果。

    drawow 或仅使用plt.ion()plt.draw()plt.pause() 的等价物都不能在jupyter 笔记本中工作。确保不使用%matplotlib inline 后端(因为您不能为 png 设置动画);但也不适用于%matplotlib notebook 后端,因为事件循环在显示最终数字之前尚未启动。

    在 jupyter notebook 中显示动画的选项列在 Animation in iPython notebook.

    推荐的方法是创建一个FuncAnimation

    上面的动画看起来像

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

    【讨论】:

    • 谢谢,但您的代码正在堆叠数字而不是更新它们。
    • 在最后一次迭代(最终图)中,您应该只看到一个点 (x[9,:])。
    • 真的吗?那么drawnow 每次通话都会清除数字?
    • 是的,如果您在 pycharm 或任何其他 IDE 中运行我的代码,它将动态绘制每个点。在每次迭代中,您将当前点绘制在同一个图形上。该点将从一个位置跳转到下一个位置。
    • 我明白了。它甚至会清除完整的数字。如果你问我,效率很低。顺便说一句,drawnow page 明确指出它在 IPython 中不起作用(因此在 Juypter 中也不起作用)。我更新了答案。
    【解决方案2】:

    您是否尝试过在 Jupyter 笔记本中使用带有 notebook 后端的 matplotlib?

    您可以通过在笔记本开头的单元格中添加 %matplotlib notebook 魔术命令来做到这一点(例如,在导入 matplotlib 之后立即)

    更多信息在这里:http://ipython.readthedocs.io/en/stable/interactive/plotting.html

    【讨论】:

    猜你喜欢
    • 2017-02-01
    • 2016-10-10
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 2022-01-20
    • 1970-01-01
    相关资源
    最近更新 更多