如何在Jupyter notebook中的tqdm-loop中动态更新matplotlib图?

q5lcpyga  于 2023-03-30  发布在  其他
关注(0)|答案(1)|浏览(145)

我如何做一些事情,比如:

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进度条不消失?

smtd7mpg

smtd7mpg1#

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

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

相关问题