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 file.py
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.
#!/usr/bin/python3
import time
import multiprocessing
import os
def plot_graph(data):
from matplotlib.pyplot import plot, draw, show
print("entered plot_graph()")
plot(data)
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()
time.sleep(5)
print("exiting main")
os._exit(0) # this exits immediately with no cleanup or buffer flushing
Running file.py
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 file.py
ion()
fixes the problem. – Aquaplaneos.fork()
but keep in mind that usingos.fork()
can be tricky because you are creating a new process by copying the old process. – Leftonos.fork
method. – Spathe