Matplotlib - Force plot display and then return to main code Matplotlib - Force plot display and then return to main code python python

Matplotlib - Force plot display and then return to main code


You may use plt.show(block=False), which gets rid of the blocking directly.

For your example, this could read

from matplotlib.pyplot import plot, showdef make_plot():    plot([1,2,3])    show(block=False)    print('continue computation')print('Do something before plotting.')# Now display plot in a windowmake_plot()answer = input('Back to main and window visible? ')if answer == 'y':    print('Excellent')else:    print('Nope')


None of the presented solutions work for me. I tested them with three different IDEs PyCharm, Spyder and Pyzo, using the (currently) latest Matplotlib 2.1 under Python 3.6.

What works for me, although not optimal, is to use a plt.pause command:

import matplotlib.pyplot as pltdef make_plot():    plt.plot([1, 2, 3])#    plt.show(block=False)  # The plot does not appear.#    plt.draw()             # The plot does not appear.    plt.pause(0.1)          # The plot properly appears.    print('continue computation')print('Do something before plotting.')# Now display plot in a windowmake_plot()answer = input('Back to main and window visible? ')if answer == 'y':    print('Excellent')else:    print('Nope')


I couldn't get this to work with Canopy (not yet at least) but I could get the code to run sort of like I wanted to using the Geany IDE. This is the code that works for me, it's a very minor modification to the first block of code in the question where the show() command is moved above from the end of the file to just below the make_plot() command:

from matplotlib.pyplot import plot, draw, showdef make_plot():    plot([1,2,3])    draw()    print 'Plot displayed, waiting for it to be closed.'print('Do something before plotting.')# Now display plot in a windowmake_plot()# This line was moved up <----show()answer = raw_input('Back to main after plot window closed? ')if answer == 'y':    print('Move on')else:    print('Nope')

It doesn't do exactly what I want but it's close enough: it shows a plot to the user, waits till that plot window is closed and then moves on with the code. Ideally it shouldn't have to wait until the plot window is closed to move on with the code, but it's better than nothing I guess.

The code in the Add 2 section above also works in the same way and with no modifications needed in Geany, but I prefer this one because it's simpler. I'll update this answer If (when?) I get this to work with Canopy.