Python: close the figure window and let the program go - python

I have a python program, say, train.py. It can be run in anaconda prompt by typing:
python train.py
In train.py, some part is written for drawing and saving figures:
import matplotlib.pyplot as plt
....... #I omit these codes
plt.savefig(....)
plt.show() #this will produce a figure window
plt.close()
In implementing the program, some figures are to be generated, which will bring the program to a temporary halt, even though plt.close() present. Then I need to manually close the pop-up figure window due to plt.show() and continue the program. How to avoid this inconvenience.
It is noted that spyder can run the program continuously, with figures displayed in its console.

plt.show() is meant to be used once in a script to show all figures present. So you can create your figures and show them all at the end
fig1 = plt.figure(1)
# do something with figure 1
fig2 = plt.figure(2)
# do something with figure 2
plt.show() # show both figures

Related

Python Matplotlib, retain plot after command line script ends

After many hours searching I am looking for a straightforward answer to the question... "Is there ANY way to run a Python3 script from the command line, which generates a plot, and have the plot remain on-screen after the script ends"?
Ideally I would love to leave the plot running in the background, and have it remain interactive enough to allow for zooming, panning and resizing (don't care cabout updating data ... yet), but I'll settle for something as low-tech as just leaving the plot there, so I can rerun the same script with different data, so I can compare plots (ya, I know I can run the entire py script in the background if necessary, which is less elegant, but may be necessary).
Some possibilities that have some to mind that may or may not be possible: have the main script spawn a background/detached process that does the plotting; use threading; keep the script running while I want to zoom/pan/resize, then leave the plot in a static state (like a picture) when the script ends.
Tried maybe a dozen or so methods posted, but none work so far.
If it can't be done, please someone just give a short and simple answer that says so, so I can move on and kludge something together like writing an image file, and spawning a background shell that that displays a picture. Or possibly, going back to something low-tech like Bash, which will allow me to use GNUplot (yup, that works amazingly ok compared to matpltlib, so far).
Thanks to anyone who can save my sanity.
-G
Here is some of what I tried from other posts:
plt.show(block=False) will not even show a plot unless preceeded by a plt.pause(). even plt.draw() does not produce a plot. only plt.pause() before the plt.show(block=False) gives me a plot, and then the plot closes when the script ends
plt.pause(0.01) allows for zooming/resizing/etc while in a loop (which I can live with), but no way to leave (even a static plot) after the script ends. This is usable, if I can leave the plot on-screen after the script ends.
plt.draw(), plt.ion() gives anomalous results, including blank plots or no plots at all
You could just open the saved image figure, for example in this post
import sys
import subprocess
def openImage(path):
imageViewerFromCommandLine = {'linux':'xdg-open',
'win32':'explorer',
'darwin':'open'}[sys.platform]
subprocess.Popen([imageViewerFromCommandLine, path])
import matplotlib.pyplot as plt
import numpy as np
# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t, s)
ax.set(xlabel='time (s)', ylabel='voltage (mV)',
title='About as simple as it gets, folks')
ax.grid()
fig.savefig("test.png")
openImage('test.png')
Just use background execution.

new plot window plot every time I run my script

I'm running a simple script in ipython, and no problem to get the plot and update the figure every time I run it
plt.clf()
plt.plot(x,y,'bo')
plt.show()
However, if I try to plot multiple panels
fig, axs = plt.subplots(1,3)
axs[0].plot(x,y,'bo')
axs[1].plot(x,z,'bo')
axs[2].plot(y,z,'bo')
plt.show()
a new window with the three panels is created every time I run my scrip (unless I exit and restart the ipython session). What shall I do? Thanks!
subplots creates a new figure by default, but you can also specify which figure to plot into, if you do so then it will only open that one figure / window:
fig, axs = plt.subplots(1,3, num=1) # force to plot into figure 1

Inscribing Plot window in the console and do not want the plot window popping up separately

I am facing couple of issues. First, I wanted all the plots in a separate window. For this, I successfully changed the settings and I got the separate window. The problem is, I got all the plots in same figures, which is bad. Second issue is, how do I inscribe window pan to the Ipconsole? I donot want a separate window. I want this window inside the console?
For the first issue, you can have your plots in different figures by using figure this way:
import matplotlib.pyplot as plt
plt.figure()
# Plot your first graph(s)
plt.figure()
# Plot your other graph(s)
plt.show()
Each time you call figure, a new window is created. For more information on figure, you can check the doc

Pyplot shows image without plt.show()

I had a look at other questions on that regard, but in all other cases people had
%matplotlib inline
which caused plots to show without being prompted. I don't have it.
My plotting code looks like this:
fig, ax = plt.subplots(figsize=(17,8))
ax = plt.hist(results_df['Diff'], bins=100, density=True, histtype='step')
plt.savefig('backtester_results/figures/rf_model_lag_{n_days}_data_{lag}_lag.png',
format='png')
It's an output from testing machine learning model I'm working on and I want to put it to run for 40 hours and there will be few hundred of these plots generated in the process. So I really want them not to just get saved in a folder and not take up memory.
Do you know how to suppress this behaviour or what could be causing it?
I'm using Python 3.6 and Spyder editor. In Spyder settings I have Graphics backend set up as 'Automatic'.

Matplotlib close plot/figure automatically after viewing [duplicate]

This question already has an answer here:
view and then close the figure automatically in matplotlib?
(1 answer)
Closed 1 year ago.
So I got a small problem, but yeah, I need an answer. A created a plot with matplotlib, and after the showing I want to close it.
Of course, I visited some documentation (e.g.: https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.close.html), a lot of forums, like that: matplotlib close does not close the window, but my code isn't working for me.
I used the plt.ion() function, but when I tryed it, the plot wasn't appearing, I just saw an empty window.
After that, I used the plt.show(block = False) and I again got an empty window.
You can see the code above:
#Showing
plt.ion()
plt.show(block = False)
time.sleep(10)
plt.close("all")
As you can see, there's a delay, I would like to see a plot for ten seconds, and after close it.
Feel free, to comment to me, I appreciate that, thank you.
Do not use time.sleep(). Use the plt.pause() function.
Details/Explanation: First, you need plt.show(block=False) so that the plot is not blocked and the code executes the next command.
Second, the second command i.e. plt.pause(3) pauses the plot for 3 seconds and then goes to the next line/command.
Finally, the last line/command, plt.close("all") closes the plot automatically.
This is a script (.py) that plots an imshow and automatically close it after 3 seconds.
import matplotlib.pyplot as plt
import numpy as np
X = np.random.rand(10,10)
plt.imshow(X)
plt.show(block=False)
plt.pause(3) # 3 seconds, I use 1 usually
plt.close("all")

Categories