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")
Related
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.
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
This question already has answers here:
Matplotlib (pyplot) savefig outputs blank image
(5 answers)
Closed 4 years ago.
EDIT: This question is a duplicate. Original question's link is posted above.
I am using Python to plot a set of values which are showing good on the Python terminal (using Jupyter NoteBook) but when I save it, the saved file when opened shows an empty (completely white) photo. Here's my code:
import matplotlib.pyplot as plt
plt.plot([1,3,4])
plt.show()
plt.savefig('E:/1.png')
You should save the plot before closing it: indeed, plt.show() dislays the plot, and blocks the execution until after you close it; hence when you attempt to save on the next instruction, the plot has been destroyed and can no longer be saved.
import matplotlib.pyplot as plt
plt.plot([1,3,4])
plt.savefig('E:/1.png') # <-- save first
plt.show() # <-- then display
When you execute the show, plt clears the graph. Just invert the execution of show and savefig:
import matplotlib.pyplot as plt
plt.plot([1,3,4])
plt.savefig('E:/1.png')
plt.show()
I think the plt.show() command is "using up" the plot object when you call it. Putting the plt.savefig() command before it should allow it to work.
Also, if you're using Jupyter notebooks you don't even need to use plt.show(), you just need %matplotlib inline somewhere in your notebook to have plots automatically get displayed.
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
I'm using python's matplotlib to do some contours using contour and contourf functions. They all work fine when using show, but when I try to use draw() inside a method, I get the matplotlib window but not graph. The show() call will be done much later on the code and in a different method, and I would like to show one graph at the moment when it's done with draw(), not having to wait until the much later show(). What I'm doing wrong?
Thanks.
Have you turned interactive mode on using ion()? The following works for me on OSX, using the Tk backend and running from the shell's command line:
import matplotlib.pyplot as plt
plt.ion()
plt.figure()
for i in range(10):
plt.plot([i], [i], 'o')
plt.draw()
raw_input("done >>")
That is, as it does each loop, you see the plot change (i.e., it gets redrawn) as each point is added. Here, btw, if I instead call plt.ioff(), I don't see the figure or any updates.
IIRC ,You should be able call fig.show() multiple times. Also, check out using ipython (ipython -pylab) and http://matplotlib.sourceforge.net/users/shell.html