Search code examples
pythonmatplotlibjupyter-notebookreal-time

Get Jupyter notebook to display matplotlib figures in real-time


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

I currently see:

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

What I'd like is:

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.


Solution

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

    results in the desired outcome

    enter image description here