如何在 Jupyter 笔记本内的 tqdm 循环中动态更新 matplotlib 绘图?

Gin*_*ger 4 python matplotlib data-analysis jupyter-notebook tqdm

我该怎么做:

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) 
Run Code Online (Sandbox Code Playgroud)

但是tqdm当我更新情节时防止进度条消失?

idf*_*fah 5

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

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()
Run Code Online (Sandbox Code Playgroud)