【问题标题】:How to update interactive figure in loop with JupyterLab如何使用 JupyterLab 循环更新交互式图形
【发布时间】:2020-12-02 15:54:30
【问题描述】:

我正在尝试使用 JupyterLab 在循环中更新交互式 matplotlib 图。如果我在与循环不同的单元格中创建图形,我可以做到这一点,但我更愿意创建图形并在同一个单元格中运行循环。

简单代码示例:

import matplotlib.pyplot as plt
import time

%matplotlib widget

fig = plt.figure()

for i in range(5):
    x = list(range(i+2))
    xx = [x**2 for x in x]
    plt.clf()
    plt.plot(x, xx)
    fig.canvas.draw()
    
    time.sleep(1)

如果fig = plt.figure() 与循环在同一个单元格中,则在循环结束之前不会更新图形:

如果我在不同的单元格中创建图形,我会得到动态更新,但如果可能的话,我希望能够在同一个单元格中创建图形,因此输出位于循环下方:

我在其他问题(hereherehere)中尝试了几个答案,但是,它们似乎不适用于 JupyterLab 中的交互式图形。我使用jupyter/scipy-notebook docker 镜像作为我的环境,所以我相信一切都设置正确。

有什么方法可以在创建图形的同一单元格中获取动态更新?

【问题讨论】:

    标签: python matplotlib jupyter jupyter-lab


    【解决方案1】:

    您可以使用 asyncio,利用 IPython 事件循环:

    import matplotlib.pyplot as plt
    import asyncio
    %matplotlib widget
    fig = plt.figure()
    
    
    async def update():
        for i in range(5):
            print(i)
            x = list(range(i + 2))
            xx = [x**2 for x in x]
            plt.clf()
            plt.plot(x, xx)
            fig.canvas.draw()
            await asyncio.sleep(1)
    
    
    loop = asyncio.get_event_loop()
    loop.create_task(update());
    

    【讨论】:

    • 使用这种方法,不再可能使用interrupt the kernel(停止-)按钮停止计算。有没有解决这个问题的简单方法?
    【解决方案2】:

    如果不想使用asyncio,可以使用display(..., display_id=True)获取句柄,在上面使用.update()

    import matplotlib.pyplot as plt
    import time
    %matplotlib widget
    fig = plt.figure()
    
    hfig = display(fig, display_id=True)
    
    
    def update():
        for i in range(5):
            print(i)
            x = list(range(i + 2))
            xx = [x**2 for x in x]
            plt.clf()
            plt.plot(x, xx)
            fig.canvas.draw()
            hfig.update(fig)
            time.sleep(1)
    
    update()
    
    plt.close(fig)
    

    【讨论】:

    • 我喜欢这个解决方案的外观,但对我来说它绘制了两个图形,一个在小部件中,一个作为图像。你知道是否有办法删除第二个情节?
    • 您使用的是哪个 notebook/jupyter-lab 版本?我正在使用笔记本 6.1.4,它可以工作。 (也适用于 jupyter-lab。)我只看到没有 plt.close(fig) 的第二个情节出现
    猜你喜欢
    • 2018-10-13
    • 2018-04-28
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 2016-11-22
    相关资源
    最近更新 更多