After these instructions in the Python interpreter one gets a window with a plot:

from matplotlib.pyplot import *
# other code

Unfortunately, I don’t know how to continue to interactively explore the figure created by show() while the program does further calculations.

Is it possible at all? Sometimes calculations are long and it would help if they would proceed during examination of intermediate results.

Use matplotlib‘s calls that won’t block:

Using draw():

from matplotlib.pyplot import plot, draw, show
print('continue computation')

# at the end call show to ensure window won't close.

Using interactive mode:

from matplotlib.pyplot import plot, ion, show
ion() # enables interactive mode
plot([1,2,3]) # result shows immediatelly (implicit draw())

print('continue computation')

# at the end call show to ensure window won't close.

Use the keyword ‘block’ to override the blocking behavior, e.g.

from matplotlib.pyplot import show, plot


# your code

to continue your code.

It is better to always check with the library you are using if it supports usage in a non-blocking way.

But if you want a more generic solution, or if there is no other way, you can run anything that blocks in a separated process by using the multprocessing module included in python. Computation will continue:

from multiprocessing import Process
from matplotlib.pyplot import plot, show

def plot_graph(*args):
    for data in args:

p = Process(target=plot_graph, args=([1, 2, 3],))

print 'yay'
print 'computation continues...'
print 'that rocks.'

print 'Now lets wait for the graph be closed to continue...:'

That has the overhead of launching a new process, and is sometimes harder to debug on complex scenarios, so I’d prefer the other solution (using matplotlib‘s nonblocking API calls)


import matplotlib.pyplot as plt
# other code
# [...]

# Put
# at the very end of your script to make sure Python doesn't bail out
# before you finished examining.

The show() documentation says:

In non-interactive mode, display all figures and block until the figures have been closed; in interactive mode it has no effect unless figures were created prior to a change from non-interactive to interactive mode (not recommended). In that case it displays the figures but does not block.

A single experimental keyword argument, block, may be set to True or False to override the blocking behavior described above.

IMPORTANT: Just to make something clear. I assume that the commands are inside a .py script and the script is called using e.g. python from the console.

A simple way that works for me is:

  1. Use the block = False inside show : = False)
  2. Use another show() at the end of the .py script.

Example of file:

plt.xlabel("true ")                                                                   
plt.ylabel("predicted ")                                                              
plt.title(" the matrix")  

# Add block = False                                   = False)


# the next command is the last line of my script

You may want to read this document in matplotlib‘s documentation, titled:

Using matplotlib in a python shell

In my case, I wanted to have several windows pop up as they are being computed. For reference, this is the way:

from matplotlib.pyplot import draw, figure, show
f1, f2 = figure(), figure()
af1 = f1.add_subplot(111)
af2 = f2.add_subplot(111)
print 'continuing computation'

PS. A quite useful guide to matplotlib’s OO interface.

Well, I had great trouble figuring out the non-blocking commands… But finally, I managed to rework the “Cookbook/Matplotlib/Animations – Animating selected plot elements” example, so it works with threads (and passes data between threads either via global variables, or through a multiprocess Pipe) on Python 2.6.5 on Ubuntu 10.04.

The script can be found here: – otherwise pasted below (with fewer comments) for reference:

import sys
import gtk, gobject
import matplotlib
import pylab as p
import numpy as nx 
import time

import threading 

ax = p.subplot(111)
canvas = ax.figure.canvas

# for profiling
tstart = time.time()

# create the initial line
x = nx.arange(0,2*nx.pi,0.01)
line, = ax.plot(x, nx.sin(x), animated=True)

# save the clean slate background -- everything but the animated line
# is drawn and saved in the pixel buffer background
background = canvas.copy_from_bbox(ax.bbox)

# just a plain global var to pass data (from main, to plot update thread)
global mypass

from multiprocessing import Pipe
global pipe1main, pipe1upd
pipe1main, pipe1upd = Pipe()

# the kind of processing we might want to do in a main() function,
# will now be done in a "main thread" - so it can run in
# parallel with gobject.idle_add(update_line)
def threadMainTest():
    global mypass
    global runthread
    global pipe1main

    print "tt"

    interncount = 1

    while runthread: 
        mypass += 1
        if mypass > 100: # start "speeding up" animation, only after 100 counts have passed
            interncount *= 1.03

# main plot / GUI update
def update_line(*args):
    global mypass
    global t0
    global runthread
    global pipe1upd

    if not runthread:
        return False 

    if pipe1upd.poll(): # check first if there is anything to receive
        myinterncount = pipe1upd.recv()

    update_line.cnt = mypass

    # restore the clean slate background
    # update the data
    # just draw the animated artist
    # just redraw the axes rectangle

    if update_line.cnt>=500:
        # print the timing info and quit
        print 'FPS:' , update_line.cnt/(time.time()-tstart)

        print "exiting"

    return True

global runthread

update_line.cnt = 0
mypass = 0



global t0
t0 = threading.Thread(target=threadMainTest)

# start the graphics update thread

print "out" # will never print - show() blocks indefinitely! 

Hope this helps someone,

In many cases it is more convenient til save the image as a .png file on the hard drive. Here is why:


  • You can open it, have a look at it and close it down any time in the process. This is particularly convenient when your application is running for a long
  • Nothing pops up and you are not forced to have the windows open. This is particularly convenient when you are dealing with many figures.
  • Your image is accessible for later reference and is not lost when closing the figure window.


  • The only thing I can think of is that you will have to go and finder the folder and open the image yourself.

If you are working in console, i.e. IPython you could use as pointed out in the other answers. But if you’re lazy you could just type:

Which will be the same.

I had to also add plt.pause(0.001) to my code to really make it working inside a for loop (otherwise it would only show the first and last plot):

import matplotlib.pyplot as plt

plt.scatter([0], [1])

for i in range(10):
    plt.scatter([i], [i+1])

On my system show() does not block, although I wanted the script to wait for the user to interact with the graph (and collect data using ‘pick_event’ callbacks) before continuing.

In order to block execution until the plot window is closed, I used the following:

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

# set processing to continue when window closed
def onclose(event):
fig.canvas.mpl_connect('close_event', onclose) # this call does not block on my system
fig.canvas.start_event_loop_default() # block here until window closed

# continue with further processing, perhaps using result from callbacks

Note, however, that canvas.start_event_loop_default() produced the following warning:

C:\Python26\lib\site-packages\matplotlib\ DeprecationWarning: Using default event loop until function specific to this GUI is implemented

although the script still ran.

I also wanted my plots to display run the rest of the code (and then keep on displaying) even if there is an error (I sometimes use plots for debugging). I coded up this little hack so that any plots inside this with statement behave as such.

This is probably a bit too non-standard and not advisable for production code. There is probably a lot of hidden “gotchas” in this code.

from contextlib import contextmanager

def keep_plots_open(keep_show_open_on_exit=True, even_when_error=True):
    To continue excecuting code when is called
    and keep the plot on displaying before this contex manager exits
    (even if an error caused the exit).
    import matplotlib.pyplot
    show_original =
    def show_replacement(*args, **kwargs):
        kwargs['block'] = False
        show_original(*args, **kwargs) = show_replacement

    pylab_exists = True
        import pylab
    except ImportError: 
        pylab_exists = False
    if pylab_exists: = show_replacement

    except Exception, err:
        if keep_show_open_on_exit and even_when_error:
            print "*********************************************"
            print "Error early edition while waiting for show():" 
            print "*********************************************"
            import traceback
            print traceback.format_exc()
            print "*********************************************"
    finally: = show_original
        if pylab_exists:
   = show_original
    if keep_show_open_on_exit:

# ***********************
# Running example
# ***********************
import pylab as pl
import time
if __name__ == '__main__':
    with keep_plots_open():
        pl.plot([1,2,3], [4,5,6])     
        pl.plot([3,2,1], [4,5,6])

        pl.plot([1,2,3], [4,5,6])

        print '...'
        print '...'
        print '...'

If/when I implement a proper “keep the plots open (even if an error occurs) and allow new plots to be shown”, I would want the script to properly exit if no user interference tells it otherwise (for batch execution purposes).

I may use something like a time-out-question “End of script! \nPress p if you want the plotting output to be paused (you have 5 seconds): ” from


plt.imshow(your_second_image) # That's important 

raw_input("Press ENTER to exist") # Useful when you run your Python script from the terminal and you want to hold the running to see your figures until you press Enter

The OP asks about detatching matplotlib plots. Most answers assume command execution from within a python interpreter. The use-case presented here is my preference for testing code in a terminal (e.g. bash) where a is run and you want the plot(s) to come up but the python script to complete and return to a command prompt.

This stand-alone file uses multiprocessing to launch a separate process for plotting data with matplotlib. The main thread exits using the os._exit(1) mentioned in this post. The os._exit() forces main to exit but leaves the matplotlib child process alive and responsive until the plot window is closed. It’s a separate process entirely.

This approach is a bit like a Matlab development session with figure windows that come up with a responsive command prompt. With this approach, you have lost all contact with the figure window process, but, that’s ok for development and debugging. Just close the window and keep testing.

multiprocessing is designed for python-only code execution which makes it perhaps better suited than subprocess. multiprocessing is cross-platform so this should work well in Windows or Mac with little or no adjustment. There is no need to check the underlying operating system. This was tested on linux, Ubuntu 18.04LTS.


import time
import multiprocessing
import os

def plot_graph(data):
    from matplotlib.pyplot import plot, draw, show
    print("entered plot_graph()")
    show() # this will block and remain a viable process as long as the figure window is open
    print("exiting plot_graph() process")

if __name__ == "__main__":
    print("starting __main__")
    multiprocessing.Process(target=plot_graph, args=([1, 2, 3],)).start()
    print("exiting main")
    os._exit(0) # this exits immediately with no cleanup or buffer flushing

Running brings up a figure window, then __main__ exits but the multiprocessing + matplotlib figure window remains responsive with zoom, pan, and other buttons because it is an independent process.

Check the processes at the bash command prompt with:

ps ax|grep -v grep |grep

In my opinion, the answers in this thread provide methods which don’t work for every systems and in more complex situations like animations. I suggest to have a look at the answer of MiKTeX in the following thread, where a robust method has been found:
How to wait until matplotlib animation ends?

Here is the simplest solution I found (thread blocking code) # this avoids blocking your thread

plt.pause(1) # comment this if you do not want a time delay

# do more stuff # this prevents the window from closing on you

If you want to open multiple figures, while keeping them all opened, this code worked for me:


While not directly answering OPs request, Im posting this workaround since it may help somebody in this situation:

  • Im creating an .exe with pyinstaller since I cannot install python where I need to generate the plots, so I need the python script to generate the plot, save it as .png, close it and continue with the next, implemented as several plots in a loop or using a function.

for this Im using:

import matplotlib.pyplot as plt
#code generating the plot in a loop or function
#saving the plot
plt.savefig(var+'_plot.png',bbox_inches="tight", dpi=250) 
#you can allways reopen the plot using
os.system(var+'_plot.png') # unfortunately .png allows no interaction.
#the following avoids plot blocking the execution while in non-interactive mode 
#and the following closes the plot while next iteration will generate new instance.

Where “var” identifies the plot in the loop so it wont be overwritten.

What I have found as the best solution so the program does not wait for you to close the figure and have all your plots together so you can examine them side by side is to show all the plots at the end.
But this way you cannot examine the plots while program is running.

# stuff

numFig = 1

numFig += 1
plt.plot(x1, y1)

# other stuff

numFig += 1
plt.plot(x2, y2)

# more stuff

Use, and at the end of your script call

This will ensure that the window won’t be closed when the script is finished.