如何使用 JupyterLab 循环更新交互式图形

How to update interactive figure in loop with JupyterLab

我正在尝试使用 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() 与循环位于同一单元格中,则在循环完成之前不会更新图形:

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

我已经尝试了其他问题的几个答案(here, , and ) however, they do not seem to work with interactive figures in JupyterLab. I am using the jupyter/scipy-notebook docker 图片作为我的环境,所以我相信一切都设置正确。

有没有办法在创建图形的同一个单元格中进行动态更新?

您可以使用 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());

如果不想用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)