本文介绍了获取Jupyter笔记本以实时显示Matplotlib图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个运行很长时间的Python循环(用于机器学习),该循环定期打印输出并显示图形(使用matplotlib).在Jupyter Notebook中运行时,所有文本(stdout)都会实时显示,但是所有数字都已排队,并且直到整个循环完成才显示.

I have a long running Python loop (used for machine learning), which periodically prints output and displays figures (using matplotlib). When run in Jupyter Notebook, all the text (stdout) is displayed in real-time, but the figures are all queued and not displayed until the entire loop is done.

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

I'd like to see the figures in real-time, on each iteration of the loop. During cell execution, not when the entire cell execution is done.

例如,如果我的代码是:

For example, if my code is:

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
...

最重要的是,我希望看到计算出来的数字,而不是等到整个循环结束后才在屏幕上看到任何数字.

Most importantly, I'd like to see the figures as they are calculated, as opposed to not seeing any figures on the screen until the entire loop is done.

推荐答案

我认为问题出在您未在此处显示的部分代码中.因为它应该按预期工作.使其可运行,

I suppose the problem lies in the part of the code you do not show here. Because it should work as expected. Making it runnable,

%matplotlib inline

import matplotlib.pyplot as plt

def do_a_1_second_calculation():
    plt.pause(1)

def show_figure(i):
    plt.figure(i)
    plt.plot([1,i,3])
    plt.show()

for i in range(10):
    print(i)
    show_figure(i)
    do_a_1_second_calculation()

达到理想的结果

这篇关于获取Jupyter笔记本以实时显示Matplotlib图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 18:16
查看更多