如何在Jupyter notebook中的tqdm循环内动态更新matplotlib图表?

3

我该如何实现类似以下的功能:

from tqdm.notebook import tqdm
from matplotlib import pyplot as plt
from IPython import display

import time
import numpy as np

xx = list()

for i in tqdm(range(500)):
    xx.append(i * 0.1)
    yy = np.sin(xx)

    if i % 10 == 0:
        display.clear_output(wait=True)
        plt.plot(xx, yy)
        time.sleep(0.1) 

但是当我更新绘图时,如何保持tqdm进度条不消失?


你能删除 display.clear_output(wait=True) 这一行吗?或者这不是你想要的吗? - Derek O
@DerekO 然后我会得到许多具有增量变化的图,而不是一个被更新的单一图。 - GingerBadger
1个回答

4

这可以通过获取显示句柄并更新它来完成,而不是在每次迭代中清除显示。

from tqdm.notebook import tqdm
from matplotlib import pyplot as plt
from IPython import display

import time
import numpy as np

xx = list()

# display the initial figure and get a display handle
# (it starts out blank here)
fig, ax = plt.subplots()
dh = display.display(fig, display_id=True)

for i in tqdm(range(500)):
    xx.append(i * 0.1)
    yy = np.sin(xx)

    if i % 10 == 0:
        # generate the plot and then update the
        # display handle to refresh it
        ax.plot(xx, yy)
        dh.update(fig)
        time.sleep(0.1)

# close the figure at the end or else you
# end up with an extra plot
plt.close()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接