如何使用JupyterLab循环更新交互式图形 [英] How to update interactive figure in loop with JupyterLab

查看:83
本文介绍了如何使用JupyterLab循环更新交互式图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JupyterLab循环更新交互式matplotlib图形.如果我在与循环不同的单元格中创建图,则可以执行此操作,但是我更喜欢在该单元格中创建图并运行循环.

简单代码示例:

 将matplotlib.pyplot导入为plt导入时间%matplotlib小部件无花果= plt.figure()对于我在范围(5)中:x =列表(范围(i + 2))xx = [x in x中的x ** 2]plt.clf()plt.plot(x,xx)fig.canvas.draw()time.sleep(1) 

如果 fig = plt.figure()与循​​环位于同一单元格中,则直到循环结束时才更新图形:

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

我已经尝试了其他问题的几个答案(

I am trying to update an interactive matplotlib figure while in a loop using JupyterLab. I am able to do this if I create the figure in a different cell from the loop, but I would prefer to create the figure and run the loop in the same cell.

Simple Code Example:

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)

If fig = plt.figure() is in the same cell as the loop the figure is not updated until the loop finishes:

If I create the figure in a different cell I get the dynamic update, but I would like to be able to create the figure in the same cell if possible so the output is below the loop:

I have tried several answers in other questions (here, here, and here) however, they do not seem to work with interactive figures in JupyterLab. I am using the jupyter/scipy-notebook docker image as my environment, so I believe everything is set up correctly.

Is there any way to get the dynamic update in the same cell as the figure is created?

解决方案

You can use asyncio, taking advantage of the IPython event loop:

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

这篇关于如何使用JupyterLab循环更新交互式图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆