Keep matplotlib / pyplot windows open after code completion

I want python to create a graph, display it without blocking the control flow, and leave the graph open after the code exits. Is it possible?

This and related topics exist (see below) in many other threads, but I cannot force the chart to remain open and not block. For example, if I use pyplot.ion() before pyplot.show() , or if I use pyplot.show(block=False) , then the chart closes when the code exits. This is true using either python or ipython . If that matters, I am running OS X 10.8.2 (Mountain Lion), starting python27 and ipython27

Related discussions:
pylab matplotlib "show" waits until the window closes
Is there a way to separate the matplotlib plots so that the calculation can continue?
Open print window in Matplotlib
Closing tower windows

+6
source share
2 answers

On Linux, you can turn off display as follows:

 import matplotlib.pyplot as plt import matplotlib.mlab as mlab import numpy as np import os def detach_display(): mu, sigma = 0, 0.5 x = np.linspace(-3, 3, 100) plt.plot(x, mlab.normpdf(x, mu, sigma)) plt.show() if os.fork(): # Parent pass else: # Child detach_display() 

The main process ends, but the schedule remains.


Attempt No. 2. It also works on Linux; , you can try: but not on OS X.

 import matplotlib.pyplot as plt import matplotlib.mlab as mlab import numpy as np import os import multiprocessing as mp def detach_display(): mu, sigma = 0, 0.5 x = np.linspace(-3, 3, 100) plt.plot(x, mlab.normpdf(x, mu, sigma)) plt.show() proc = mp.Process(target=detach_display) proc.start() os._exit(0) 

Without os._exit(0) , the main blocks of the process. Pressing Ctrl-C kills the main process, but the plot remains.

With os._exit(0) main process ends, but the graph remains.


Sigh. Attempt number 3. If you put your matplotlib calls in another script, you can use the subprocess as follows:

show.py:

 import matplotlib.pyplot as plt import numpy as np import sys filename = sys.argv[1] data = np.load(filename) plt.plot(data['x'], data['y']) plt.show() 

test.py

 import subprocess import numpy as np import matplotlib.mlab as mlab mu, sigma = 0, 0.5 x = np.linspace(-3, 3, 100000) y = mlab.normpdf(x, mu, sigma) filename = '/tmp/data.npz' np.savez(filename, x=x, y=y) proc = subprocess.Popen(['python', '/path/to/show.py', filename]) 

Running test.py should display the graph and control the return to the terminal, leaving the displayed graph.

+6
source

Although this cannot directly answer the question, the simplest practical thing I found is to use (use show (block = False) and) run the script in the background. That way, the graph will remain, and you will be returned to the shell prompt, and the script ends when you kill the graph window ...

-1
source

All Articles