【问题标题】:Live plotting in Jupyter Lab 3 using Matplotlib在 Jupyter Lab 3 中使用 Matplotlib 进行实时绘图
【发布时间】:2021-06-13 17:21:53
【问题描述】:

我想动态更新单元格的绘图。 IE。该图在单元格的开头初始化,并在(计算量大的)for循环中更新,显示计算的进展情况。在jupyter notebook 中,这可以使用pneumatics solution 中的What is the currently correct way to dynamically update plots in Jupyter/iPython? 来完成

%matplotlib notebook

import numpy as np
import matplotlib.pyplot as plt
import time

def pltsin(ax, colors=['b']):
    x = np.linspace(0,1,100)
    if ax.lines:
        for line in ax.lines:
            line.set_xdata(x)
            y = np.random.random(size=(100,1))
            line.set_ydata(y)
    else:
        for color in colors:
            y = np.random.random(size=(100,1))
            ax.plot(x, y, color)
    fig.canvas.draw()

fig,ax = plt.subplots(1,1)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_xlim(0,1)
ax.set_ylim(0,1)
for f in range(5):
    pltsin(ax, ['b', 'r'])
    time.sleep(1)

我正在jupyter lab 中寻找等效的方法。我尝试使用ipympl 库将%matplotlib notebook 替换为%matplotlib widget,但这不起作用:该图仅在循环完成后显示。

我不想要像Ziofil in 或Paidoo in jupyterlab interactive plot 那样的解决方案,它们会清除整个输出,因为我可能会打印其他内容,例如一个tqdm进度条

【问题讨论】:

标签: matplotlib jupyter-lab ipywidgets


【解决方案1】:

这是一个众所周知的 matplotlib,很高兴有一些解决方法。 相关问题为:https://github.com/matplotlib/matplotlib/issues/18596https://github.com/matplotlib/ipympl/issues/258 最长的解释可能是https://github.com/matplotlib/ipympl/issues/290#issuecomment-755377055

这两种变通方法都适用于 ipympl。

解决方法 1

在这个答案之后使用异步 ipython 事件循环:https://stackoverflow.com/a/63517891/835607

解决方法 2

plt.subplots 和更新的绘图代码拆分为两个单元格。如果您在执行单元格之间等待一两秒钟,那么绘图将有足够的时间来正确设置自己并且它应该都可以工作。看起来像这样:

单元格 1:

fig,ax = plt.subplots(1,1)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_xlim(0,1)
ax.set_ylim(0,1)

等到情节出现然后执行: 单元格 2:

for f in range(5):
    pltsin(ax, ['b', 'r'])
    time.sleep(1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-26
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多