Python Matplotlib, retain plot after command line script ends - python

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.

Related

how to plot the image predicted by keras [duplicate]

The behavior of matplotlib's plot and imshow is confusing to me.
import matplotlib as mpl
import matplotlib.pyplot as plt
If I call plt.show() prior to calling plt.imshow(i), then an error results. If I call plt.imshow(i) prior to calling plt.show(), then everything works perfectly. However, if I close the first figure that gets opened, and then call plt.imshow(i), a new figure is displayed without ever calling plt.show().
Can someone explain this?
If I call plt.show() prior to calling
plt.imshow(i), then an error results.
If I call plt.imshow(i) prior to
calling plt.show(), then everything
works perfectly.
plt.show() displays the figure (and enters the main loop of whatever gui backend you're using). You shouldn't call it until you've plotted things and want to see them displayed.
plt.imshow() draws an image on the current figure (creating a figure if there isn't a current figure). Calling plt.show() before you've drawn anything doesn't make any sense. If you want to explictly create a new figure, use plt.figure().
... a new figure is displayed without ever
calling plt.show().
That wouldn't happen unless you're running the code in something similar to ipython's pylab mode, where the gui backend's main loop will be run in a separate thread...
Generally speaking, plt.show() will be the last line of your script. (Or will be called whenever you want to stop and visualize the plot you've made, at any rate.)
Hopefully that makes some more sense.

Different plots with show and savefig

I am plotting histograms with quite large number of bins. I am using Spyder, Python 3.6.3. The problem I found is that the figure I am seeing in iPython console is NOT the same as the saved plots. I have seen this thread which asks a similar question, however, my problem is worse, as it's not just the fonts and sizes that vary, I am actually getting different counts!
E.g. the same script:
plt.clf()
fig, ax=plt.subplots()
fig.dpi=100
plt.hist(df['POS'], bins=nbins, range=(0,dict_l[c]))
plt.savefig('current_chr17.jpg', dpi=100)
will produce this plot as a saved figure:
and show this in iPython console (interactive mode on, I'm not even asking for plt.show):
Does anyone have any explanation as to what is going on?

Python: close the figure window and let the program go

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

how to stop pyplot from popping up figures

I write a number of plots to a pdf with a loop like the following. It works but there are two very annoying issues,
1) When the loop runs, i see a lot of windows ('Figure 1') popped up. I think the command plt.close(fig) does not work as intended. This' really annoying because I might be doing something else when it runs and those pop-ups block my view to the other tasks.
2) Probably related to 1), memory usage goes up dramatically. In my real script, plotting something like 50 pages of graphs eats up > 32 Gb of ram. How could that be?!
with PdfPages('Manyplots.pdf') as pdf:
for j in xrange(100):
fig = plt.figure(1, figsize=(5,5))
for fr in xrange(9):
pp = fig.add_subplot(3,3,fr+1)
pp.imshow(x, cmap=plt.cm.gray)
pdf.savefig()
plt.close(fig)
My questions are
1) any way to close a figure after the plot is done?
2) better still, how to suppress blank Figure pop-up since it should really be writing to an external file in the background,
3) any better way to save a series of plots to multiple pages of PDF?
Found the cause of the problem. My main script includes an import of someone's utility script, which imports pyplot and has an extra line,
import matplotlib.pyplot as plt
plt.ion()
When plt.ion is commented out, the popups are gone.

matplotlib draw showing nothing

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

Categories