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.
Related
I am trying to follow some of the guides for generating real-time plots such as: real-time plotting in while loop with matplotlib and http://thread.gmane.org/gmane.comp.python.matplotlib.general/35705
However, I believe the sample code was compiled with python 2.7. When I try to compile mine I do not see a real-time plot being updated. Is this because python 3 doesn't support it? Or am I missing a library or something? Only when I stop the while loop I see the last value that was plotted. I am using Rodeo as my IDE; would this be preventing me from viewing the real-time plot?
import serial
import numpy as np
import matplotlib.pyplot as plt
def plotlive():
plt.plot(ard_dat,'o')
plt.xlabel('count', fontsize=12)
plt.ylabel('reading', fontsize=12)
plt.legend(loc='upper right')
ard_dat=[]
plt.ion()
cnt=0
arduinoSerialData = serial.Serial('com5',9600)
while True:
while (arduinoSerialData.inWaiting()==0):
pass
srdata = arduinoSerialData.readline()
try:
intstrdata = int(srdata)
except ValueError:
pass
ard_dat.append(intstrdata)
drawnow(plotlive)
plt.pause(.00001)
cnt+=1
if (cnt>50):
ard_dat.pop(0)
There is no specific python 2 or 3 command in the code so you can leave that out of the equation.
I would not recommend to use drawnow. Call plotlive() directly instead. This is however just a recommendation because drawnow is a pretty useless package, but it would not prevent the code from running.
Assuming that the serial works fine, the code from the question should produce an updating plot when being run as script.
The main point is this: Rodeo is not capable of producing animations. See this issue: https://github.com/yhat/rodeo/issues/488
The reason is that it uses a notebook-like output mechanism. While in Jupyter notebook you would actually be able to set the backend to interactive mode (%matplotlib tk or %matplotlib notebook), this is apparently not possible in Rodeo.
Rodeo also does not seem to have the option to run some code as python script outside of its IDE. Therefore the idea would be to either use a different IDE or to at least run animations outside of Rodeo.
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))
I'm plotting some graphs and then I interact with them using the canvas.mpl_connect commands. So when I show the plot, I want the window to be the active one since the beginning.
At the moment, when the script is run, the plot pops up but it's not the active window, the terminal still is (i.e. if I type a key, that is written in the Terminal, and not interpreted by the plot-window). I need to click on the plot-window to make it the active one and then I'm able to interact with the graphs. It would be way nicer if it was already active the first time it pops up.
Working on MacOSX 10.10.3 with python 2.7.5 and matplotlib 1.3.1
EDIT
I don't just need to bring the window in front, I want to be able to interact with the window without having to click on it. So if I type some keys, the graph will respond and not the terminal.
You can set the order windows are displayed in using canvas manager but it only works with some graphical backends. The following example uses the TkAgg backend which works but the same idea won't work the macosx backend.
import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt
from pylab import get_current_fig_manager
fig1 = plt.figure()
fig2 = plt.figure()
fig1.canvas.manager.window.attributes('-topmost', 1)
plt.show()
Figure 1 should show up on top of figure 2.
So, I've finally found a solution here https://github.com/matplotlib/matplotlib/pull/663
Apparently a work around is to import
from AppKit import NSApplication
and issuing just before show():
NSApplication.sharedApplication().activateIgnoringOtherApps_(True)
I'm not really sure what it does, and apparently it works just in non-interactive mode, but that worked perfectly for me.
You might also want to check here
https://github.com/matplotlib/matplotlib/issues/665/
I am trying to use Python and the numpy and matplotlib libraries to do some data analysis and plotting and view my plots, adjust my code accordingly etc. So I need to be able to examine the plot. However, running the script from the command line causes the figure to pop up momentarily then instantly disappear. Another answer suggested to add a raw_input("text here") line at the end of the program to force python to wait for input and hold the plots open. This does hold the plot windows open for me but the actual plots disappear and I just get an empty gray figure window while python waits for input.
I'm running MAC OS X 10.8.3 and using the terminal v2.3 and my python installation is python 2.7.3
import matplotlib.pylab as plt
import numpy as np
[ .. bunch of calculations .. ]
plt.ion()
plt.figure("Test Figure")
plt.plot(xspace[:],vals[:,50])
raw_input("press key to exit")
Use plt.show at the end of your code.
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")