matplotlib - 使用 Matplotlib 在 Jupyter Lab 3 中实时绘图

标签 matplotlib jupyter-lab ipywidgets

我想动态更新单元格的绘图。 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 提出的那样的解决方案。在或一个Paidoojupyterlab interactive plot这会清除整个输出,因为我可能会打印其他内容,例如一个 tqdm 进度条

最佳答案

这是 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)

关于matplotlib - 使用 Matplotlib 在 Jupyter Lab 3 中实时绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66655001/

相关文章:

python - 我可以在 rcParams 中设置 spine 和 ticks 吗?

matplotlib - 使用 Julia Plots 访问后端特定功能

python - 使用 savefig() 从 matplotlib 导出时如何指定 .eps 的大小(尺寸)

post - 错误启动内核 : '_xsrf' argument missing from POST

python-3.x - Ipywidgets Jupyter Notebook 交互忽略参数

python - 在轴之间移动集合

python - jupyter 按顺序打印图和数据框,for 循环

python-3.x - jupyter 实验室中的 Bqplot 返回字符串而不是(交互式)图像

ipython - 如何使 jupyter notebook 中的小部件可滚动?

python - 以编程方式运行 ipyvuetify 按钮