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.
Related
The code example below runs without error, but nothing is displayed to the screen.
Here's the code example that I'm trying to use...
import SchemDraw
import SchemDraw.elements as elm
d = SchemDraw.Drawing()
R1 = d.add(elm.Resistor(label='1K$\Omega$'))
d.labelI(R1, '1 mA', top=False)
d.add(elm.Capacitor(d='down', botlabel='0.1$\mu$F'))
d.add(elm.Line( d='Left'))
d.add(elm.Ground)
d.add(elm.SourceV( d='up', label='10V') )
d.save('schematic.svg')
d.draw()
I'm on a Windows 7 platform and I have Python 3.7 integrated into my command prompt. If I navigate to the directory where my schematic.py file is located and I add this into the console:
Python schematic.py
It runs fine and exits with 0 error, but nothing is drawn to the screen, Matplotlib isn't even invoked...
After searching through some documents, brief tutorials, or examples that are very limited, I've come to realize that the above example, as well as others, rely on Jupyter Notebook with Matplotlib inlined...
How am I able to draw this without using Jupyter Notebook and inlining Matplotlib directly?
I would like to run it as a basic Python script and I know I can import the Matplotlib module manually like this...
import Matplotlib.pyplot as plt
//... prev code
d.draw() // doesn't draw anything to the screen or to matplotlib's backend...
// plt.plot(...)? What goes here?
plt.show()
But I don't know how to use it to draw the results from SchemDraw's draw method...
Losing the Matplotlib interactive window was a regression bug introduced in SchemDraw 0.7. It was fixed in 0.7.1, pushed to PyPi today. In this version, d.draw() opens the Matplotlib window if running as a script, or shows output in the cell if running in Jupyter inline mode.
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 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'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 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.