python plot doesn't display a window - python

When I run this simple code:
from pylab import *
import numpy as np
X = [];
Y = [];
for i in range (0,10):
X.append(i)
Y.append(i)
plot(X,Y)
show()
I don't get any window. I tried to replace show with draw with the same result.
I'm using python version 3.2.2
How can I show the window/plot than (apart from printing it to file and open the file).
Note, I'm using this example:
http://matplotlib.sourceforge.net/examples/api/custom_scale_example.html

I don't think numpy or scipy have a stable release for 3.2 yet.
Unless it's important to you that you use python 3.2, try to install python 2.7 instead. Everything should work fine there.

Related

Numpy and Matplotlib Error with very Minimal Example

I have been using numpy and matplotlib together for some time now, successfully. Suddenly, I am getting unusual errors when using them together. The following is a minimal example:
import numpy as np
import matplotlib.pyplot as plt
fig,ax = plt.subplots(1,1)
x = np.eye(10)
u = np.linalg.svd(x)
plt.show()
If I run the code once, it works. If I run the code again, I get an exception:
LinAlgError: SVD did not converge. Bizarrely, this behavior disappears when the call to pyplot is removed:
import numpy as np
import matplotlib.pyplot as plt
#fig,ax = plt.subplots(1,1)
x = np.eye(10)
u = np.linalg.svd(x)
#plt.show()
I tried this with two different python environments with numpy versions 18.1 and 18.5. I am wondering if anyone has any information about what could possibly cause this behavior.
edit: I was running these two blocks of code in a jupyter notebook with only those lines of code and nothing else. In order to reproduce the behavior in the interactive interpreter, you need to add the line plt.show() in between runs. I edited the post to include this line.
edit: matplotlib 3.3.2, numpy 18.1 or 18.5, and I can use python 3.8.1 or 3.6.8

How to avoid PyCharm console crash "WARNING: QApplication was not created in the main() thread" when plotting with matplotlib?

In PyCharm, when I try to plot something using its interactive console, such as:
In[2]: from matplotlib.pyplot import *
In[3]: x = range(5)
In[4]: y = range(5,10)
In[5]: plot(x,y)
WARNING: QApplication was not created in the main() thread.
Out[5]: [<matplotlib.lines.Line2D at 0x7fade916a438>]
In[6]: show()
It opens a window and crashes. I have to stop the console and start a new one.
It works fine when I run anything like that in an ipython console in my terminal, the error happens only in Pycharm, it seems.
On the other hand, if import matplotlib with import matplotlib.pyplot as plt it works fine:
In[2]: import matplotlib.pyplot as plt
In[3]: x = range(5)
In[4]: y = range(5,10)
In[5]: plt.plot(x,y)
Out[5]: [<matplotlib.lines.Line2D at 0x7fd3453b72e8>]
In[6]: plt.show()
But if I do both, it crashes too (even calling the plot function using plt.plot):
In[2]: from matplotlib.pyplot import *
In[3]: import matplotlib.pyplot as plt
In[4]: x = range(5)
In[5]: y = range(5,10)
In[6]: plt.plot(x,y)
WARNING: QApplication was not created in the main() thread.
Out[6]: [<matplotlib.lines.Line2D at 0x7fade916a438>]
In[7]: plt.show()
Furthermore, when I run it all in one command, it works the first time. But if I try to plot another time, it crashes:
In[2]: from matplotlib.pyplot import *
...: x = range(5)
...: y = range(5,10)
...: plot(x,y)
...: show()
In[3]: plot(x,y)
WARNING: QApplication was not created in the main() thread.
Out[3]: [<matplotlib.lines.Line2D at 0x7fc68a3009e8>]
In[4]: show()
So it is something related with using the matplotlib library with the import using * and with running in the interactive console after the first time it was imported. I know the wildcard import is not recommended, but sometimes it is useful to do it for a sake of testing things faster and being less verbose.
Looking for this warning online, I have only found these
https://github.com/matplotlib/matplotlib/issues/13296
But my case doesn't seem to be related to multiprocessing. And even if pycharm is doing something behind the scenes, I wonder why it has changed, as I had no problems with this like a month ago;
Suppress warning "QApplication was not created in main() thread"
and other posts related to C++, which is not my case;
WARNING: QApplication was not created in main() thread -> related to pycharm, but has an additional error different than mine
Which didn't help much. Anyone knows what is happening and how to solve it?
SPECS:
PyCharm 2019.1.2 (Professional Edition)
Build #PY-191.7141.48, built on May 7, 2019
JRE: 11.0.2+9-b159.56 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Linux 4.15.0-50-generic
conda 4.6.14, with Python 3.7.3
Qt5
I sent this question to JetBrains: https://youtrack.jetbrains.com/issue/PY-36136
They couldn't find a solution yet, but the workaround they suggested is the following:
Disable Show plots in tool window in File | Settings | Tools | Python Scientific.
This worked for me, although it doesn't plot in the PyCharm window.
There several things you can try:
First, you can try to update the Qt. You may have some older version. Run
print(plt.get_backend())
to verify which backend you are using. If you are using Qt4, try Qt5 back end.
Next, update Qt5 to the latest version via
pip install --upgrade PyQt5
Also, you can try ditching Qt and switch to Tk back end: add
import matplotlib
matplotlib.use('TkAgg')
before importing pyplot

Python Spyder Display Symbolic Math

In Spyder 2 (Anaconda distribution) and in the IPython QT Console I'm able to print results of symbolic calculations (from an answer I got for a previous post) but I can't get equations in strings to print with the a IPython's Rich Display System:
from sympy import *
from IPython.display import display, Math
init_printing(use_unicode=False, wrap_line=False, no_global=True)
x, y, z = symbols('x y z')
#----- prints correctly
ii = integrate(x**2 + x + 1, x)
display(ii)
#----- does not print
Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx')
The above prints the results of the integrate correctly but the Math() does not print (no error -- just skips it). Note it all works in SciPy web notebook.
Thank you!
The Math class doesn't generate the rendered image from your Latex, that's why it doesn't work directly.
To get what you want you need to use this code
from IPython.display import Image, display
from IPython.lib.latextools import latex_to_png
eq = r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx'
data = latex_to_png(eq, wrap=True)
display(Image(data=data))
Then you will see the right image
Hello guys im still having the problem, whe i use
from IPython.display import display, Math, Latex
display((Math(r'P(Purchase|Male)= \frac{Numero\ total\ de\ compras\ hechas\ por\ hombres\}{Total\ de\ hombres\ en\ el\ grupo\} = \frac{Purchase\cap Male}{Male}')))
on jupyter it works fine, but when i do the exact same code on spyder it doesnt work
im using python 3.6 , spyder 3.3.3
also i tried the marked asnwer but latex_to_png makes a NoneType Object on spyder

Why matplotlib does not plot?

I started to learn MatPlotLib using this tutorial for beginners. Here is the first example.
from pylab import *
X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)
If I write these 3 lines into my python file and execute it in the command line (by typing python file_name.py), nothing happens. No error message, no plot.
Does anybody know why I do not see the plot?
ADDED
Of course I need to use show. But even if I add the following 3 lines:
plot(X,C)
plot(X,S)
show()
it still does no generate anything.
ADDED
Here are the lines that I use now:
import pylab as p
C = [1,2,3,4]
S = [10, 20, 30, 10]
p.plot(C,S)
p.show()
I still have the same result (nothing).
It could be a problem with the backend.
What is the output of
python -c 'import matplotlib; import matplotlib.pyplot; print(matplotlib.backends.backend)'?
If it is the 'agg' backend, what you see is the expected behaviour as it is a non-interactive backend that does not show anything to the screen, but work with plt.savefig(...).
You should switch to, e.g., TkAgg or Qt4Agg to be able to use show. You can do it in the matplotlib.rc file.
#shashank: I run matplotlib both on 12.04 and 12.10 without problems. In both cases I use the Qt4Agg backend. If you don't have the matplotlibrc set, the default backend is used.
I'm sure that for Precise matplotlib repo was built with TkAgg. If the Quantal version has been built with e.g. Agg, then that would explain the difference
You need to call the function:
show()
to be more exact:
pylab.show()
and even better don't use:
from pylab import *
rather do:
import pylab as p:
and then:
X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)
p.plot(C,S)
p.show()
Try adding. I use Jupyter and this worked for me.
%matplotlib inline

matplotlib.pyplot/pylab not updating figure while isinteractive(), using ipython -pylab [duplicate]

This question already has answers here:
pylab.ion() in python 2, matplotlib 1.1.1 and updating of the plot while the program runs
(2 answers)
Closed 8 years ago.
There are a lot of questions about matplotlib, pylab, pyplot, ipython, so I'm sorry if you're sick of seeing this asked. I'll try to be as specific as I can, because I've been looking through people's questions and looking at documentation for pyplot and pylab, and I still am not sure what I'm doing wrong. On with the code:
Goal: plot a figure every .5 seconds, and update the figure as soon as the plot command is called.
My attempt at coding this follows (running on ipython -pylab):
import time
ion()
x=linspace(-1,1,51)
plot(sin(x))
for i in range(10):
plot([sin(i+j) for j in x])
#see **
print i
time.sleep(1)
print 'Done'
It correctly plots each line, but not until it has exited the for loop. I have tried forcing a redraw by putting draw() where ** is, but that doesn't seem to work either. Ideally, I'd like to have it simply add each line, instead of doing a full redraw. If redrawing is required however, that's fine.
Additional attempts at solving:
just after ion(), tried adding hold(True) to no avail.
for kicks tried show() for **
The closest answer I've found to what I'm trying to do was at plotting lines without blocking execution, but show() isn't doing anything.
I apologize if this is a straightforward request, and I'm looking past something so obvious. For what it's worth, this came up while I was trying to convert matlab code from class to some python for my own use. The original matlab (initializations removed) which I have been trying to convert follows:
for i=1:time
plot(u)
hold on
pause(.01)
for j=2:n-1
v(j)=u(j)-2*u(j-1)
end
v(1)= pi
u=v
end
Any help, even if it's just "look up this_method" would be excellent, so I can at least narrow my efforts to figuring out how to use that method. If there's any more information that would be useful, let me know.
from pylab import *
import time
ion()
tstart = time.time() # for profiling
x = arange(0,2*pi,0.01) # x-array
line, = plot(x,sin(x))
for i in arange(1,200):
line.set_ydata(sin(x+i/10.0)) # update the data
draw() # redraw the canvas
pause(0.01)
print 'FPS:' , 200/(time.time()-tstart)
ioff()
show()
########################
The above worked for me nicely. I ran it in spyder editor in pythonxy2.7.3 under win7 OS.
Note the pause() statement following draw() followed by ioff() and show().
The second answer to the question you linked provides the answer: call draw() after every plot() to make it appear immediately; for example:
import time
ion()
x = linspace(-1,1,51)
plot(sin(x))
for i in range(10):
plot([sin(i+j) for j in x])
# make it appear immediately
draw()
time.sleep(1)
If that doesn't work... try what they do on this page: http://www.scipy.org/Cookbook/Matplotlib/Animations
import time
ion()
tstart = time.time() # for profiling
x = arange(0,2*pi,0.01) # x-array
line, = plot(x,sin(x))
for i in arange(1,200):
line.set_ydata(sin(x+i/10.0)) # update the data
draw() # redraw the canvas
print 'FPS:' , 200/(time.time()-tstart)
The page mentions that the line.set_ydata() function is the key part.
had the exact same problem with ipython running on my mac. (Enthought Distribution of python 2.7 32bit on Macbook pro running snow leopard).
Got a tip from a friend at work. Run ipython from the terminal with the following arguments:
ipython -wthread -pylab
This works for me. The above python code from "Daniel G" runs without incident, whereas previously it didn't update the plot.
According to the ipython documentation:
[-gthread, -qthread, -q4thread, -wthread, -pylab:...] They provide
threading support for the GTK, Qt (versions 3 and 4) and WXPython
toolkits, and for the matplotlib library.
I don't know why that is important, but it works.
hope that is helpful,
labjunky
Please see the answer I posted here to a similar question. I could generate your animation without problems using only the GTKAgg backend. To do this, you need to add this line to your script (I think before importing pylab):
matplotlib.use('GTkAgg')
and also install PyGTK.

Categories