At the end of the last function I call in one of my programs, I have the following code to plot a simple color plot.
plt.figure()
plt.pcolormesh(X,Y,Z)
plt.colorbar()
plt.show()
Afterwords I return to main and my program is complete. The plot displays as expected, however when I go to close it using the x button in the corner (on ubuntu), my program doesn't end. It just hangs there with a process running. How can I correct this?
your matplotlib might be running in non-interactive mode for some reason.
I am not sure how to prevent that in your local configuration but if you add either this:
plt.ion()
or this:
matplotlib.interactive(True)
somewhere at the beginning of your script, it should change the behaviour of your plots.
For interactive mode, You need this at the head of file:
import matplotlib
matplotlib.use("TkAgg")
Related
I want to save a plot created using matplotlib to a file but I do not want it to show as inline plot in Spyder IDE. My code:
import matplotlib.pyplot as plt
from math import sin,pi
import numpy as np
x = np.linspace(0,2*pi,100)
y = np.sin(x)
plt.plot(x,y)
plt.savefig('sin.png')
When I run this code, the plot keep showing in IPython console as inline plot whereas I just want to save it to a file. How can I fix this problem?
add plt.close() after plt.savefig().
This behaviour is steered by some of the settings in spyder.
First, you may of course opt not to use IPython at all. Instead if the script is executed in a new python console, it will not pop up at all without you specifying plt.show() at the end.
If however you want to use IPython, but not get any graphical output, you may deactivate the graphical output for the IPython console. I.e. no checkmark at "Activate support". This will then also require you to call plt.show() to actually show the figure in a new window.
Note that changing those settings will require to restart Spyder.
Those are the general settings. If you want this behaviour only for a single script, use plt.close() at the end of a cell/script.
I want to show plots in a separate window. Currently I have the IPython graphics backend set to "automatic".
When I re-run the code (or plot another figure), Spyder opens a new plot window. Is it possible to refresh the figure in the window that is already opened instead of opening a new one?
The GUI window that opens when you call plt.show() is bound to a figure. You cannot change the figure inside it. (Well, to be precise, there might be an option of obtaining a handle from the operating system and manipulating its content, but I assume this is not worth the effort.)
Re-running the code actually means that you produce a new figure since the code does not know that it's been run before.
So, exchanging the figure or reusing the window to plot a different figure is not possible.
What is possible however is to use the figure and manipulate the figure while it's open. This is done via plt.ion(). After calling this command in IPython you can adapt the figure, e.g. adding new lines to it etc.
See this example:
At IN [6] the window opens and when IN [7] is executed, the figure stays open and the content changes.
Sure, it is possible with Spyder while in the same running kernel. Try the following example using num as parameter to plt.figure(), where num will always refer to the same figure and refresh it if already opened. Also works with plt.subplots().
import matplotlib.pyplot as plt
from scipy import *
t = linspace(0, 0.1,1000)
w = rand(1)*60*2*pi
fig = plt.figure(num=10, clear=True, figsize = [10,8])
plt.plot(t,cos(w*t))
plt.plot(t,cos(w*t-2*pi/3))
plt.plot(t,cos(w*t-4*pi/3))
So I have some python code that plots a few graphs using pyplot. Every time I run the script new plot windows are created that I have to close manually. How do I close all open pyplot windows at the start of the script? Ie. closing windows that were opened during previous executions of the script?
In MatLab this can be done simply by using closeall.
To close all open figures from a script, you can call
plt.close('all')
or you can terminate the associated Python process.
This solution won't allow you to close plots from previous runs, but will prevent you from leaving them open!
The only way I have found to close these "hanging" figures is to find the process and kill.
Plot in a non blocking manner then ask for input. This should prevent you from forgetting to properly close the plot.
plt.show(block=False)
plt.pause(0.001) # Pause for interval seconds.
input("hit[enter] to end.")
plt.close('all') # all open plots are correctly closed after each run
import matplotlib.pyplot as plt
plt.close("all")
(In case you have pyplot already imported, you obviously don't need to import it again. In that case just make sure to replace plt in plt.close("all") with whatever alias you chose for pyplot when you imported it.)
I just had the same problem. I call a function that generates multiple plot windows. Each time I call the function the popped up plot windows accumulate in number. Trying matplotlib.pyplot.close('All') at the begining of the function didn't solve the problem. I solved the problem by calling matplotlib.pyplot.close(figure), where figure is a plot figure instance (object).
I maintain a list of my plot figure objects. So, it is a good idea to maintain a list, and then call matplotlib.pyplot.close(figure) for each instance of a figure object:
import matplotlib.pyplot as plot
Add plot instance objects (figure,axis) to a list:
fig, (ax1,ax2) = plt.subplots(nrows=2)
figAxisDict = {'figure': fig, 'axis1': ax1, 'axis2':ax2}
figAxisList.append(figAxisDict)
Call the function for figure closing, and clear the list afterwards:
if len(figAxisList) !=0:
for figAxis in figAxisList:
figure=figAxis['figure']
plot.close(figure)
figAxisList[:]=[]
As there seems no absolutely trivial solution to do this automatically from the script itself: the possibly simplest way to close all existing figures in pycharm is killing the corresponding processes (as jakevdp suggested in his comment):
Menu Run\Stop... (Ctrl-F2). You'll find the windows closed with a delay of few seconds.
Honestly, the developer needs to make this a simple function like it is in MATLAB.
My temporary solution for Spyder:
first install keyboard and pynput via the Anaconda Prompt
in Spyder run "mouse.position" with your mouse over the position where your plots pane is
These coordinates are the ones you need to replace in the code below.
import keyboard
from pynput.mouse import Button, Controller
#%% Clear Old Plots
#Selects the mouse as the controller
mouse = Controller()
#Record current mouse position
recmp = mouse.position
#Set pointer position on plots pane
mouse.position = (1136,370) # <-- replace coordinates here with yours!
#Opens the plot pane
keyboard.press_and_release('ctrl+shift+g')
#Click and release left mouse button
mouse.press(Button.left)
mouse.release(Button.left)
#Runs close all in the plots pane
keyboard.press_and_release('ctrl+shift+w')
#Resets mouse position to the original location
mouse.position = recmp
On *nix you can use killall command.
killall app
closes every instance of window with app for the window name.
You can also use the same command from inside your python script.
You can use os.system("bashcommand") to run the bashcommand.
I have noticed that when I run:
import pylab as pl
pl.ion()
# Plot something
pl.show()
pl.close()
The last statement does not fully close the Figure. The figure goes dark, and the contents go away, but the Figure stays on the screen until I exit IPython as shown below
I am using the latest stable version of matplotlib (1.3.1) using an Anaconda distribution, on Linux 64 bit, and I connect remotely using ssh -X.
The backend I am using is below:
backend : QT4Agg
backend.qt4 : PySide
you have to specify wich figure you want to close. In case you want to close all of them:
pl.close('all')
Also, there is a way to just clear but not close a figure:
pl.clf()
Also, seen below from another SO question:
Remember that plt.show() is a blocking function, so in the example code you used above, plt.close() isn't being executed until the window is closed, which makes it redundant.
You can use plt.ion() at the beginning of your code to make it non-blocking, although this has other implications.
You can also use the following lines after your plotting
#Your Plotting function
plt.waitforbuttonpress(0)
plt.close(fig)
The plt.waitforbuttonpress(0) will wait until a user input (Key press) is given. After that it will properly close the matplotlib window properly. It is very important to specify which figure to close.
I am using matplotlib to draw charts and graphs.
When I plot the chart using the command show() my code blocks at this command.
I would like to refresh my list of values with new data , and than refresh the image on the background. How to do that without closing each time the window with the graph?
Below is the code I am using
import pylab
a = (1,2,3,4)
pylab.plot(a)
pylab.show() # blocks here
In IPython started with -pylab it should not block.
Otherwise:
With ion() you turn the interactive mode on. show() does not block your system
anymore. Every draw() or plot(x, y) updated your plot.
ioff() turns interactive mode off. Useful if you add lots of data and don't
want to update every little detail.
See also: http://www.scipy.org/Cookbook/Matplotlib/Animations
If you are not using the IPython shell but instead running a program, you probably want to do:
pyplot.draw()
after a plot(), possibly followed by
raw_input("Press enter when done...")
so as to wait for the user before plotting something else.
If you do pyplot.ion() at the beginning of your program, doing draw() can often even be skipped.
pyplot.show() is actually an infinite loop that handles events in the main plotting window (such as zooming, panning, etc.).
On MacOS X i had the problem that unblocking only produced a white screen. In the end #tyleha's suggestion using %pylab directly in the note book helped.
In fact it's suggested when using the deprecated the -pylab flag:
bash:~/Projects/plyground $ python -m IPython notebook -pylab
WARNING: `-pylab` flag has been deprecated.
Use `--matplotlib <backend>` and import pylab manually.
[E 21:09:05.446 NotebookApp] Support for specifying --pylab on the command line has been removed.
[E 21:09:05.447 NotebookApp] Please use `%pylab` or `%matplotlib` in the notebook itself.
This works by invoking Ipython with the -wthread (or the -pylab) option. It will not block on show anymore.