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.
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'm getting the error
QPixmap: It is not safe to use pixmaps outside the GUI thread
when manually entering the following statements in Seaborn in the ipython-shell using PyDev in Eclipse:
import matplotlib.pyplot as mpl
import seaborn as sns
import pandas as pd
import numpy as np
# Turn interactive mode off:
mpl.ioff()
# Create some example Data:
df = pd.DataFrame({'A':np.random.rand(20),'B':np.random.rand(20)})
# Create seaborn PairGrid instance:
pg = sns.PairGrid(df)
At this point when I continue the last statement with a dot to e.g. chain a map()-method, like this:
pg = sns.PairGrid(df).
then Eclipse is trying to show a popup of all possible completions but that popup is immediatly getting closed and the console is getting filled with the aforementioned error, 42 lines of it to be precise.
I can continue and do this without problem:
gp = sns.PairGrid(df).map(mpl.scatter)
gp.fig.show()
And I get my plot just fine.
The same happens when doing sns.JointGrid(df.A,df.B). and sns.FacetGrid(df).
While playing around earlier I also got into situations where the console was actually killed by this error, I just can't replicate the steps that lead to this anymore.
Researching on this site it looked like it has to do with threading which I'm not using at all. Does Seaborn use it?
I want to create my plots by first creating a Grid/Figure and doing the plotting later, but this error suggests that this isn't a safe way to do things though the Seaborn doc says it's fine to do it like that:
https://seaborn.github.io/generated/seaborn.FacetGrid.html
EDIT:
When doing the same thing in Spyder I'm not getting the error but this warning when doing gp.fig.show():
C:\Anaconda2\lib\site-packages\matplotlib\figure.py:397: UserWarning:
matplotlib is currently using a non-GUI backend, so cannot show the figure
"matplotlib is currently using a non-GUI backend, "
When interactive mode is off I'm not seeing any graphic. With interactive mode on I'm still seeing the warning but get the graphic inline.
No popup in either case though. In Eclipse I'm getting both the error and the popup.
EDIT 2:
Running the whole thing as a script in Eclipse does not produce any error, only the manual entering like described above does.
I took a look at https://github.com/fabioz/Pydev/blob/master/plugins/org.python.pydev/pysrc/pydevconsole.py and the issue is that the code-completion on PyDev is being triggered in a secondary thread, not in the main (UI) thread.
I.e.: the code completion in the interactive console is not expecting that it'll touch code that'll actually interact with the gui.
For this to work, the completion command has to be queued for the main thread (as the regular commands are queued) and the thread has to wait for it to finish to then return its value.
Please report this as an issue in the PyDev tracker: https://www.brainwy.com/tracker/PyDev/ (i.e.: code-completion in the interactive console should happen in the UI thread).
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.