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

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.

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.

When is plt.show() required to show a plot and when is it not?

Since the following code will show a plot without plt.show(), what is the point of plt.show()?
Please tell me when plt.show() is required as this would allow me to appreciate the intricacy of matplotlib better.
N.B.: I'm using this in Spyder (Anaconda)
import matplotlib.pyplot as plt
plt.subplot(211) # the first subplot in the first figure
plt.plot([1, 2, 3])
To require or not required depending on where your script is.
There are 2 contexts.
Matplotlib is used in a terminal or scripts, plt.show() is a must.
Matplotlib is used in a IPython shell or a notebook (ex: Kaggle), plt.show() is unnecessary.
It seems either you are in an interactive mode or are using a JuPyter notebook, in both the cases plt.show() being rendered redundant (check the bold highlighted doc below)
From the official docs
Display a figure. When running in ipython with its pylab mode, display all figures and return to the ipython prompt.
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.

plt.ioff() isn't working. How do I plot several different graphs

plt.ioff()
for i in range(0,len(variableList)):
graph = lag1['VDC'].rolling(window=24).corr(other=lag1[variableList[i]])
plt.title(variableList[i])
plt.plot(graph)
plt.axhline(y=0)
plt.savefig(variableList[i])
I want to plot several different independent graphs. The default is in interactive mode where each new graph is plotted on the previous one. I read the document and found that I need to use plt.ioff(). However adding this line doesn't change anything.
If you try the example in non-interactive example, Usage Guide, the output is a set of three graphs indeed. Furthermore, plt.ioff() doesn't work if you set %matplotlib inline.
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
plt.ioff()
for i in range(3):
plt.plot(np.random.rand(10))
plt.show()
However, it saves plots with lines accumulated if you use plt.savefig.
%matplotlib inline
plt.ioff()
for i in range(3):
plt.plot(np.random.rand(10))
plt.savefig(f'{i}.png')
Also, it doesn't work if:
%matplotlib auto
plt.ioff()
for i in range(3):
plt.plot(np.random.rand(10))
plt.show()
So, for non-interactive figures, you should always use object-oriented (OO) style to avoid such issues:
%matplotlib auto
plt.ioff()
for i in range(3):
fig, ax = plt.subplots()
ax.plot(np.random.rand(10))
fig.savefig(f'{i}.png')
The interactive mode is used to obtain an event loop while continuiung the execution of the script. This can be useful to update a plot at several different points in a script, for doing quick animations or for working from within the console.
The interactive mode has nothing to do with new figures being created. I.e. you can have several figures or only one figure, both with interactive mode on or off.
To obtain a new figure in pyplot use
plt.figure()
pyplot commands executed after that will apply to this new figure.
The pyplot tutorial has a chapter on Working with multiple figures and axes, where this is explained in detail.

SVG rendering issues using iPython inline plots

when I use inline plots in iPython (QtConsole), the first plot looks (more or less) fine, but then it gets weirder and weirder. When I plot something several times (so plot, see it displayed, plot again, see output etc.), it looks like it is being overlaid with the skewed previous picture. So after plotting a diagonal line (x=y) 4 times in a row I get something like this
If i right click and export it as svg everything looks good
(Exported PNG picture remains wrecked as the first one).
I guess the problem is similar to https://github.com/ipython/ipython/issues/1866, but I didn't got the upshot of the discussion (it got too technical and complicated for me to follow).
Is there any solution or work around for this issue?
I'm using
python 2.7
matplotlib 1.4.1
IPython 2.1.0
Here is a working example:
%matplotlib inline
% config InlineBackend.figure_format = 'svg'
import matplotlib.pyplot as plt
a=range(10)
fig,ax=plt.subplots()
ax.plot(a,a)
ax.axis('off')
if you remove plt.axis('off') line, weird things happen only outside of the axis box.
P.S. Originally I encountered this problem in connection with drawing graphs with networkx. If I use draw from networkx this problem does not occur. If I use draw_networkx, same as described above happens. That might point to the core of the problem... I'm trying to figure out what line of code makes one work better than the other...
After tinkering around with the draw and draw_networkx functions from networkx module, I found the workaround which makes the difference between draw and draw_networkx in this case.
Adding fig.set_facecolor('w') overlays whatever is in the background, so the new plots are started with a white sheet (but not a blank one, I guess).
So new working example is:
%matplotlib inline
% config InlineBackend.figure_format = 'svg'
import matplotlib.pyplot as plt
a=range(10)
fig,ax=plt.subplots()
fig.set_facecolor('w')
ax.plot(a,a)
ax.axis('off')

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