how to plot the image predicted by keras [duplicate] - python

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.

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.

In which specific cases are the two used - matplotlib.pyplot.imshow() and matplotlib.pyplot.show()?

I went through the documentation of both but the documentation does not specify for a specific use case for both. I have also found that sometimes the imshow() property on its own displays the figures but sometimes the show() property needs to be used to display the figure. In the documentation , the imshow() property mentions about displaying the image on the axes but the word "axes" is missing from the show() property. What does the word axes more specifically refer to?
imshow() documentation
show() documentation
Except for both, imshow and show having the word "show" in them, they have nothing in common.
imshow is a plotting command. It is hence on the same level as other plotting commands like plot, scatter, pcolor, contour etc. Those plotting command will produce some graphical data representation inside an axes. An axes is essentially the rectangle you see around your plot.
plt.show() is the command you need to give at the end to produce the graphical output. It is the function which makes the figure which has previously been produced by one or more plotting commands to actually show up on screen - hence the name "show".
So you usually have
import matplotlib.pyplot as plt
<plotting command>
plt.show()
E.g.
plt.scatter(...)
plt.show()
or
plt.imshow(...)
plt.show()
Now in some cases, depending on the environment where you run your code, the use of plt.show() is not needed. This is because the environment is aware of there being a matplotlib plot being generated and it will therefore generate its output automatically for you without the need to call plt.show(). This would be mainly inside of IPython sessions or Jupyter notebooks.
In summary: In order to produce a plot with an image, you call plt.imshow(..). Whether or not you then need to call plt.show() to invoke the representation on screen depends on the environment. In case you do not want to show the image on screen, but e.g. save it to a file instead, you would omit plt.show() and call
plt.imshow(...)
plt.savefig(...)
instead.
well as you can see in the doc, imshow displays an image while show displays a figure.
Imshow's arguments are array_type objects, such as a jpeg picture (which can be of shape n x m x 3 for coloured, or n x m for black and white.
When you run a script that calls methods as .plot(), or hist(), you need to call .show() to display them.
To display your image, you call imshow().
Hope it helps.

Difference between plt.draw() and plt.show() in matplotlib

I was wondering why some people put a plt.draw() into their code before the plt.show(). For my code, the behavior of the plt.draw() didn't seem to change anything about the output. I did a search on the internet but couldn't find anything useful.
(assuming we imported pyplot as from matplotlib import pyplot as plt)
plt.show() will display the current figure that you are working on.
plt.draw() will re-draw the figure. This allows you to work in interactive mode and, should you have changed your data or formatting, allow the graph itself to change.
The plt.draw docs state:
This is used in interactive mode to update a figure that has been altered using one or more plot object method calls; it is not needed if figure modification is done entirely with pyplot functions, if a sequence of modifications ends with a pyplot function, or if matplotlib is in non-interactive mode and the sequence of modifications ends with show() or savefig().
This seems to suggest that using plt.draw() before plt.show() when not in interactive mode will be redundant the vast majority of the time. The only time you may need it is if you are doing some very strange modifications that don't involve using pyplot functions.
Refer to the Matplotlib doc, "Interactive figures" for more information.

Save figure parameters after interactive tweaking

I often find myself using matplotlib to quickly display data, then later going back and tweaking my plotting code to make pretty figures. In this process, I often use the interactive plot window to adjust things like spacing, zooming, cropping, etc. While I can easily save the resulting figure to an image file, what I really want is to save the sequence of function calls/parameters that produced it.
Note that I don't particularly care to open the same figure again (as in Saving interactive Matplotlib figures). Even something as simple as being able to print the various properties of the figure and axes would be useful.
While I don't have the answer to your specific question, I'd generally suggest using the Ipython Notebook for these things (and much more!)
Make sure you have %pylab inline in one cell.
When you plot, it will display it in the notebook itself. Then within your cell, just keep experimenting until you have it right (use Ctrl-Enter in the cell). Now the cell will have all the statements you need (and no more!)
The difference between the command line interpreter and the notebook is that the former all statements you typed which leads to a lot of clutter. With the notebook you can edit the line in place.
A similar question here
has an answer I just posted here.
The gist: use MatPlotLib's picklable figure object to save the figure object to a file. See the aforementioned answer for a full example.
Here's a shortened example:
fig, ax = matplotlib.pyplot.subplots()
# plot some stuff
import pickle
pickle.dump( fig, open('SaveToFile.pickle', 'wb') )
This does indeed save all plotting tweaks, even those made by the GUI subplot-adjuster. Unpickling via pickle.load() still allows you to interact via CLI or GUI.

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