Detach matplotlib window from sub-process - python

I've got a script which creates a graph, but the script keeps running in the background until the window is closed. I'd like it to quit as soon as the window is created, so that Ctrl-C in the shell won't kill the window, and so that the user can leave the window open and continue working in the shell without bg-ing it manually. I've seen some solutions with daemons, but I'd like to avoid splitting this into two scripts. Is multiprocessing the easiest solution, or is there something shorter?
The relevant show() command is the last thing that is executed by the script, so I don't need to keep a reference to the window in any way.
Edit: I don't want to save the figure as a file, I want to be able to use the interactive window. Essentially the same as running mian ... & in bash

Just discovered this argument in plt.show(). setting block=False will pop up the figure window, continue following code, and keep you in the interpreter when the script has finished (if you are running in interactive mode -i).
plt.show(block=False)

This works for Unix:
import pylab
import numpy as np
import multiprocessing as mp
import os
def display():
os.setsid()
pylab.show()
mu, sigma = 2, 0.5
v = np.random.normal(mu,sigma,10000)
(n, bins) = np.histogram(v, bins=50, normed=True)
pylab.plot(bins[:-1], n)
p=mp.Process(target=display)
p.start()
When you run this script (from a terminal) the pylab plot is displayed. Pressing Ctrl-C kills the main script, but the plot remains.

I would suggest using os.fork() as the simplest solution. It is the trick that is used in daemons, but it doesn't require two scripts, and it's quite simple. For example:
import os
proc_num = os.fork()
if proc_num != 0:
#This is the parent process, that should quit immediately to return to the
#shell.
print "You can kill the graph with the command \"kill %d\"." % proc_num
import sys
sys.exit()
#If we've made it to here, we're the child process, that doesn't have to quit.
import matplotlib.pyplot as plt
plt.plot([1,2,3],[4,5,6])
plt.show()

Related

how to run code pyautogui after plt.show()

I want move a chart after run plt.show() but my code pyautogui dont run unless I close the chart. I searched on Google but inefficient.
plt.show()
pyautogui.hotkey('winleft', 'left')
pyautogui.hotkey('winleft', 'up')
pyautogui.press('esc')
before:
and after code "pyautogui":
What you want is a way to have plt.show() be "non-blocking", that is, have the function call return immediately instead of waiting for the user to close the window. To do this, pass block=False. So your code should be:
plt.show(block=False)
pyautogui.hotkey('winleft', 'left')
pyautogui.hotkey('winleft', 'up')
pyautogui.press('esc')
Threading might be a suitable method. Here's an example:
import numpy as np
from matplotlib import pyplot as plt
import pyautogui
import time
from threading import Thread
def pressKeys():
time.sleep(1)
pyautogui.hotkey('winleft', 'left')
pyautogui.hotkey('winleft', 'up')
pyautogui.press('esc')
t1 = Thread(target=pressKeys)
t1.start()
plt.plot([1,2,3],[1,8,27])
plt.show()
With threading, there's the main thread, which is what your program normally runs in, and then you can create additional ones. In concocting this example, I found that, unfortunately, matplotlib encounters errors when not run in the main thread.
If your objective is to make the plot full screen, then there are better ways to do it than pyautogui (there's probably some function in the windows api). Short of that, you could at least make sure that the window is open before pressing the keys (Hence the call to time.sleep.) Better yet (but more time consuming -- not the module/import), use matplotlib to set the title and use psutil to periodically check if a a process exists with that title, then when one does, break from a loop and trigger the key presses.

Interactive Matplotlib window not updating

I have a programme which creates an interactive matplotlib (well, pylab) figure, then waits for a raw_input while letting the user manipulate the plot to manually find the best data.
import pylab as p
p.ion()
p.figure(1)
p.plot(x,y,'.')
cen=float(raw_input('Type centre:'))
dur=float(raw_input('Type duration:'))
depth=float(raw_input('Type depth:'))
If I run this on linux (matplotlib 1.4.3), it works as expected. Running this on my Mac (matplotlib 1.5.0) freezes the pylab window at it's first draw and doesn't let the interactive features work. After something is entered into the raw_input, however, it draws all the preceding interactive clicks. Any ideas?
ion() and raw_input() do not work well together. This is a known problem. In interactive mode pyplot.ion() is using an event handler to wait for keypresses. This breaks when raw_input takes over the input.
You can make it a bit better by adding draw() or show():
import pylab as p
p.ion()
p.figure(1)
p.plot(x,y,'.')
p.show()
cen=float(raw_input('Type centre:'))
dur=float(raw_input('Type duration:'))
depth=float(raw_input('Type depth:'))

How to prevent ipython shutting down interactive mode while running a script

This page talks about the usage of ipython for interactive plotting: http://matplotlib.org/users/shell.html
According to that page, by default the %run command that is used to run scripts in ipython shuts down interactive mode. Is there an option to run the script in interactive mode as well?
I want the plotting commands in a script to take effect in the plotting figure as soon as they are run as if they are entered from the console interactively.
For example, consider the very simple script below:
# try.py:
# run in ipython that is started with
# ipython --pylab
# using
# %run -i try.py
from numpy import *
from time import sleep
ion()
x = randn(10000)
hist(x,100)
show()
sleep(5)
xlabel('labalu')
When run from ipython as indicated in the comment, this script waits 5 seconds, than shows everything. What I want is this: When run from ipython as indicated in the comment, the script should show the histogram immediately, wait 5 seconds, than update the figure to show the x label.
Moving ion() so it is after show() does what I think you want. Why it doesn't in the higher position, I do not know offhand.
If wx is used as the backend, following works:
#run in ipython that is started with ipython --pylab=wx
from numpy import *
import matplotlib
matplotlib.use('WX')
import wx
from time import sleep
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
x = np.random.uniform(0,1,100)
plt.plot(x)
plt.show()
wx.Yield()
for i in reversed(range(5)):
print(i)
sleep(1)
plt.xlabel('labl')
wx.Yield()
So, wx.Yield() lets interaction with the figure window. This also works when the script is run with normal python, but the figure is closed at the end of the script automatically.
Any cross-backends solutions (or solutions for qt/tk ) are still well come.
And below is a solution that works with both the wx and qt backends. gcf().canvas.flush_events() does the trick.
# try.py:
# run in ipython that is started with
# ipython --pylab
# using
# %run -i try.py
from numpy import *
import matplotlib
from time import sleep
x = randn(10000)
hist(x,100)
show()
ion()
gcf().canvas.flush_events()
sleep(5)
xlabel('labalu')
show()

Matplotlib - Force plot display and then return to main code

This is a MWE of what I'm after, adapted from this question:
from matplotlib.pyplot import plot, draw, show
def make_plot():
plot([1,2,3])
draw()
print 'continue computation'
print('Do something before plotting.')
# Now display plot in a window
make_plot()
answer = raw_input('Back to main and window visible? ')
if answer == 'y':
print('Excellent')
else:
print('Nope')
show()
What I want is: I call the function to make the plot, the plot window appears, and then I get to go back to the prompt so I can input some value (based on that image that just displayed) and carry on with the code (the window can then close or remain there, I don't care).
What I get instead is that the window with the plot only appears after the code is completed, which is no good.
Add 1
I've tried the following with the same results, the plot window appears at the end of the code and not before:
from matplotlib.pyplot import plot, ion, draw
ion() # enables interactive mode
plot([1,2,3]) # result shows immediately (implicit draw())
# at the end call show to ensure window won't close.
draw()
answer = raw_input('Back to main and window visible? ')
if answer == 'y':
print('Excellent')
else:
print('Nope')
The same happens if I change draw() for show().
Add 2
I've tried the following approach:
from multiprocessing import Process
from matplotlib.pyplot import plot, show
def plot_graph(*args):
for data in args:
plot(data)
show()
p = Process(target=plot_graph, args=([1, 2, 3],))
p.start()
print 'computation continues...'
print 'Now lets wait for the graph be closed to continue...:'
p.join()
which results in a Python kernel has crashed error in Canopy with the message:
The kernel (user Python environment) has terminated with error code -6. This may be due to a bug in your code or in the kernel itself.
Output captured from the kernel process is shown below.
[IPKernelApp] To connect another client to this kernel, use:
[IPKernelApp] --existing /tmp/tmp9cshhw.json
QGtkStyle could not resolve GTK. Make sure you have installed the proper libraries.
[xcb] Unknown sequence number while processing queue
[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
[xcb] Aborting, sorry about that.
python: ../../src/xcb_io.c:274: poll_for_event: La declaración `!xcb_xlib_threads_sequence_lost' no se cumple.
I should mention I'm running Canopy in elementary OS which is based in Ubuntu 12.04.
Add 3
Also tried solution posted in this question:
import numpy
from matplotlib import pyplot as plt
if __name__ == '__main__':
x = [1, 2, 3]
plt.ion() # turn on interactive mode
for loop in range(0,3):
y = numpy.dot(x, loop)
plt.figure()
plt.plot(x,y)
plt.show()
_ = raw_input("Press [enter] to continue.")
This displays empty plot windows as the code advances (ie: the user hits [enter]) and only displays the images after the code is finished.
This solution (also in the same question) doesn't even display the plot windows:
import numpy
from matplotlib import pyplot as plt
if __name__ == '__main__':
x = [1, 2, 3]
plt.ion() # turn on interactive mode, non-blocking `show`
for loop in range(0,3):
y = numpy.dot(x, loop)
plt.figure() # create a new figure
plt.plot(x,y) # plot the figure
plt.show() # show the figure, non-blocking
_ = raw_input("Press [enter] to continue.") # wait for input from the user
plt.close() # close the figure to show the next one.
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, show
def make_plot():
plot([1,2,3])
show(block=False)
print('continue computation')
print('Do something before plotting.')
# Now display plot in a window
make_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 plt
def 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 window
make_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, show
def 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 window
make_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.

Is there a way to detach matplotlib plots so that the computation can continue?

After these instructions in the Python interpreter one gets a window with a plot:
from matplotlib.pyplot import *
plot([1,2,3])
show()
# 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
plot([1,2,3])
draw()
print('continue computation')
# at the end call show to ensure window won't close.
show()
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.
show()
Use the keyword 'block' to override the blocking behavior, e.g.
from matplotlib.pyplot import show, plot
plot(1)
show(block=False)
# 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:
plot(data)
show()
p = Process(target=plot_graph, args=([1, 2, 3],))
p.start()
print 'yay'
print 'computation continues...'
print 'that rocks.'
print 'Now lets wait for the graph be closed to continue...:'
p.join()
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)
Try
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.show(block=False)
# other code
# [...]
# Put
plt.show()
# 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 script.py from the console.
A simple way that works for me is:
Use the block = False inside show : plt.show(block = False)
Use another show() at the end of the .py script.
Example of script.py file:
plt.imshow(*something*)
plt.colorbar()
plt.xlabel("true ")
plt.ylabel("predicted ")
plt.title(" the matrix")
# Add block = False
plt.show(block = False)
################################
# OTHER CALCULATIONS AND CODE HERE ! ! !
################################
# the next command is the last line of my script
plt.show()
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)
af1.plot([1,2,3])
af2.plot([6,5,4])
draw()
print 'continuing computation'
show()
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: Animating_selected_plot_elements-thread.py - otherwise pasted below (with fewer comments) for reference:
import sys
import gtk, gobject
import matplotlib
matplotlib.use('GTKAgg')
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
# http://docs.python.org/library/multiprocessing.html#pipes-and-queues
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
pipe1main.send(interncount)
time.sleep(0.01)
return
# 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
canvas.restore_region(background)
# update the data
line.set_ydata(nx.sin(x+(update_line.cnt+myinterncount)/10.0))
# just draw the animated artist
ax.draw_artist(line)
# just redraw the axes rectangle
canvas.blit(ax.bbox)
if update_line.cnt>=500:
# print the timing info and quit
print 'FPS:' , update_line.cnt/(time.time()-tstart)
runthread=0
t0.join(1)
print "exiting"
sys.exit(0)
return True
global runthread
update_line.cnt = 0
mypass = 0
runthread=1
gobject.idle_add(update_line)
global t0
t0 = threading.Thread(target=threadMainTest)
t0.start()
# start the graphics update thread
p.show()
print "out" # will never print - show() blocks indefinitely!
Hope this helps someone,
Cheers!
In many cases it is more convenient til save the image as a .png file on the hard drive. Here is why:
Advantages:
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
time.
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.
Drawback:
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 plt.show(block=False) as pointed out in the other answers. But if you're lazy you could just type:
plt.show(0)
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])
plt.draw()
plt.show(block=False)
for i in range(10):
plt.scatter([i], [i+1])
plt.draw()
plt.pause(0.001)
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)
ax.plot(x,y)
# set processing to continue when window closed
def onclose(event):
fig.canvas.stop_event_loop()
fig.canvas.mpl_connect('close_event', onclose)
fig.show() # 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\backend_bases.py:2051: DeprecationWarning: Using default event loop until function specific to this GUI is implemented
warnings.warn(str,DeprecationWarning)
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
#contextmanager
def keep_plots_open(keep_show_open_on_exit=True, even_when_error=True):
'''
To continue excecuting code when plt.show() 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 = matplotlib.pyplot.show
def show_replacement(*args, **kwargs):
kwargs['block'] = False
show_original(*args, **kwargs)
matplotlib.pyplot.show = show_replacement
pylab_exists = True
try:
import pylab
except ImportError:
pylab_exists = False
if pylab_exists:
pylab.show = show_replacement
try:
yield
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()
show_original()
print "*********************************************"
raise
finally:
matplotlib.pyplot.show = show_original
if pylab_exists:
pylab.show = show_original
if keep_show_open_on_exit:
show_original()
# ***********************
# Running example
# ***********************
import pylab as pl
import time
if __name__ == '__main__':
with keep_plots_open():
pl.figure('a')
pl.plot([1,2,3], [4,5,6])
pl.plot([3,2,1], [4,5,6])
pl.show()
pl.figure('b')
pl.plot([1,2,3], [4,5,6])
pl.show()
time.sleep(1)
print '...'
time.sleep(1)
print '...'
time.sleep(1)
print '...'
this_will_surely_cause_an_error
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 https://stackoverflow.com/questions/26704840/corner-cases-for-my-wait-for-user-input-interruption-implementation.
plt.figure(1)
plt.imshow(your_first_image)
plt.figure(2)
plt.imshow(your_second_image)
plt.show(block=False) # 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 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
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)
plt.show(block=False) # this avoids blocking your thread
plt.pause(1) # comment this if you do not want a time delay
# do more stuff
plt.show(block=True) # 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:
show(block=False)
draw()
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
plt.show(block=False)
#and the following closes the plot while next iteration will generate new instance.
plt.close()
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
plt.figure(numFig)
numFig += 1
plt.plot(x1, y1)
# other stuff
plt.figure(numFig)
numFig += 1
plt.plot(x2, y2)
# more stuff
plt.show()
Use plt.show(block=False), and at the end of your script call plt.show().
This will ensure that the window won't be closed when the script is finished.

Categories

Resources