代码之家  ›  专栏  ›  技术社区  ›  SRobertJames

让Jupyter笔记本实时显示Matplotlib数字

  •  4
  • SRobertJames  · 技术社区  · 7 年前

    我有一个长时间运行的python循环(用于机器学习),它定期打印输出并显示数字(使用matplotlib)。当在Jupyter笔记本中运行时,所有文本(stdout)都会实时显示,但这些数字都会排队,直到完成整个循环后才会显示。

    我想在循环的每次迭代中实时地看到这些数字。在单元执行期间,而不是整个单元执行完成时。

    例如,如果我的代码是:

    for i in range(10):
      print(i)
      show_figure(FIG_i)
      do_a_10_second_calculation()
    

    我现在看到:

    0
    1
    2
    ...
    9
    FIG_0
    FIG_1
    ...
    FIG_9
    

    我想要的是:

    0
    FIG_0
    1
    FIG_1
    2
    FIG_2
    ...
    

    最重要的是,我希望在计算数字时看到它们,而不是在整个循环完成之前在屏幕上看不到任何数字。

    2 回复  |  直到 7 年前
        1
  •  2
  •   ImportanceOfBeingErnest    7 年前

    我想问题在于您在这里没有显示的代码部分。因为它应该按预期工作。使其可运行,

    %matplotlib inline
    
    将matplotlib.pyplot导入为plt
    
    def do_a_1_second_calculation():
    暂停(1)
    
    def显示图(i):
    图(I)
    plt.绘图([1,i,3])
    显示()
    
    对于范围(10)内的i:
    打印(一)
    秀图(一)
    做一秒钟的计算
    < /代码> 
    
    

    结果达到预期结果

    结果达到预期结果

    enter image description here

        2
  •  1
  •   tel    7 年前

    display function from ipython.display. can be used to immediately flush a figure to cell output.假设您的代码中的 fig_i->code>是一个实际的matplotlib图形对象,您可以只替换 show_figure(fig_i)- with display(fig_i)->code>and the figures will output in real time.

    以下是 display in action:的完整示例:

    从Matplotlib导入Pyplot as plt 将numpy导入为np 从ipython.display导入显示 从时间导入睡眠 对于范围(0、11、5)内的eps: 数据=np.random.randint(eps,eps+10,大小=(2,10)) 图=plt.图()) AX=图GCA-() 图(*数据) print('eps%f'%eps) 显示器(图) plt.close().close防止单元执行结束时显示正常图形 睡眠(2) print('休眠2秒') < /代码>

    以下是输出的屏幕截图:

    IPython.display 可用于立即将数字刷新到单元格输出。假设 FIG_i 在您的代码中是一个实际的matplotlib figure对象,您只需替换 show_figure(FIG_i) 具有 display(FIG_i) 这些数字将实时输出。

    下面是一个完整的例子 显示 行动中:

    from matplotlib import pyplot as plt
    import numpy as np
    from IPython.display import display
    from time import sleep
    
    for eps in range(0, 11, 5):
        data = np.random.randint(eps, eps+10, size=(2,10))
    
        fig = plt.figure()
        ax = fig.gca()
    
        ax.plot(*data)
    
        print('eps %f' % eps)
        display(fig)
        plt.close()    # .close prevents the normal figure display at end of cell execution
    
        sleep(2)
        print('slept 2 sec')
    

    以下是输出的屏幕截图:

    enter image description here