qiskit plots not showing up in spyder console - python

System Informations
Qiskit version: 0.17.0
Python version: 3.7.7
Operating system: Windows 10 home x64
What is the current behavior?
I am using spyder 4.1.1 on Anaconda and any time I try to plot data it does not show up. The code runs with no errors but the plot it self does not appear anywhere.
Steps to reproduce the problem
Running the code listed below which is from the IBMQ website:
import numpy
import qiskit as qc
from qiskit import QuantumCircuit, execute, Aer
import matplotlib
from qiskit.visualization import plot_state_city
circ = qc.QuantumCircuit(3)
circ.h(0)
circ.cx(0,1)
circ.cx(0,2)
print(circ.draw())
backend = Aer.get_backend('statevector_simulator')
job = execute(circ, backend)
result = job.result()
outputstate = result.get_statevector(circ, decimals=3)
print(outputstate)
plot_state_city(outputstate)
What is the expected behavior?
for the plot state city plot to show up in the console or somewhere else
Suggested solutions
I tried using both matplotlib.pylot.show() and matplotlib.pyplot.draw()

Try follow the instructions under "Spyder plots in separate windows" here. Then you can also call circ.draw(output='mpl') to draw the circuit in a window. Hope this helps.

To print your circuit, you have to type print(name of the circuit) so in your case type print(circ).

This may be because the plots don't show in spyder by default. If you run this code in a Jupyter Notebook the plots should show up just fine!

I generally use pycharm ide for running the qiskit code. I think, spyder should also work the same.
Please modify your code as below. I hope, it will work for you.
import numpy
import qiskit as qc
from qiskit import QuantumCircuit, execute, Aer
import matplotlib
from qiskit.visualization import plot_state_city
import matplotlib.pyplot as plt
circ = qc.QuantumCircuit(3)
circ.h(0)
circ.cx(0,1)
circ.cx(0,2)
circ.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator')
job = execute(circ, backend)
result = job.result()
outputstate = result.get_statevector(circ, decimals=3)
print(outputstate)
plot_state_city(outputstate)
plt.show()

1st: I changed the preferences of spyder: Tools ==> Preferences ==> ipython console ==> Graphics ==> Graphics backend ==> Automatic.
2nd: then I have tried the option mentioned in the answer above, with minor modification is that by writing 'mpl' only between the brackets after the word "draw" to have the code be circ.draw('mpl'), and things worked fine.

Related

Module matplotlib.cm has no [color] member

I've been practicing with matplotlib, then after a short break I opened the codes again and to my surprise, got this error of missing member, which I wasn't getting before.
Module 'matplotlib.cm' has no 'Blues' memberpylint(no-member)
The thing is:
This supposedly missing member is is there, as it shows in the terminal:
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib.pyplot as plt
>>> plt.cm.Blues
<matplotlib.colors.LinearSegmentedColormap object at 0x000002D00AF42B20>
>>>
It is there. Not missing at all;
plt stands for matplotlib.pyplot, not just matplotlib, as the error suggests.
Here is the script:
import matplotlib.pyplot as plt
from random_walk_mod import RandomWalkMod
print("This program displays a random walk")
# Keep making new walks, as long s the program is active
while True:
# Make a random walk
rw = RandomWalkMod()
rw.fill_walk()
# Plot the points in the walk
plt.style.use('classic')
fig, ax = plt.subplots(figsize=(15,9), dpi=128)
point_numbers = range(rw.num_points)
ax.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues,
edgecolors='none', s=1)
# Emphasize the first and last points
ax.scatter(0,0,c='green', edgecolors='none', s=100)
ax.scatter(rw.x_values[-1],rw.y_values[-1],c='red',edgecolors='none',s=100)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
keep_running = input("Make another walk? (y/n): ")
if keep_running == 'n':
break
I have found a solution at this forum (https://www.zhihu.com/question/433655496), which is just pass in the color instead of the path, as in:
cmap='Blues'
Instead of:
cmap=plt.cm.Blues
And it works. However, it doesn't seem to wrap it up for me, because I really feel there has to be a workaround to writing the path ("plt.cm.Blues", which a few weeks ago was working fine), because:
plt refers to matplotlib.pylint, NOT just matplotlib. Why is this error pointing at plt (i.e. matplotlib.pyplot) and reporting a missing member from matplotlib.cm (i.e. ignoring pyplot)?
"cm" and its many colors are obviously there. A simple dir search proves it. Actually, both matplotlib and pyplot have an attribute called "cm", which are even the same object:
>>> dir(plt.cm) == dir(matplotlib.cm)
True
So, there are two possible paths for calling "Blues", but VSCode doesn't seem to reach them out. The objects are there and the paths are corectly written, so what is going on?
Not even importing the whole matplotlib solves the problem.
Also, I couldn't find anything related in matplotlib's docs. I hope I'm just very bad at reading docs :)
Any help is much appreciated. Thank you!
[UPDATE: solved]
I had two possible solutions for this, which would be either:
setting up pylint in settings.json so it would ignore the no-member error, or
update Python, which I just had to do.
So I chose the latter, but then VSCode wouldn't recognize the update. No matter what I did (update Python, update VSCode, uninstall and reinstall everything...), VSCode would still not show the updated python interpreter(3.9.5), but instead the old version I had(3.9.1). I set the path correctly, but to VSCode it was like I'd never updated Python.
So after some thorough research, I tried uninstalling VSCode but this time clearing its cache by deleting the folder "Code" (Win+R, then type "%appdata", hit Enter). Finally, VSCode reads the python app as expected, and, even better, the linting problem is gone.
Is it possible that VSCode is using a different python interpreter than your system python that you're using in the terminal? My guess is the VSCode python has a different version of matplotlib that would account for the inconsistency across your two scripts. Your script worked just fine for me on python 3.9.5, with matplotlib 3.4.2
You can run the code, right?
It's a problem with pylint instead of your code.
You can refer to the official docs, explaining the no-member problem in pylint.
And you can add this to the settings.josn file to fix this:
"python.linting.pylintArgs": [
"--c-extension-no-member",
]

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 (matplotlib) __NSAutoreleaseNoPool error ... - just leaking

[I originally posted this in serverfault, but was advised there to post it here instead.]
Matplotlib is a python library for data visualization. When I attempt to display a graph on the screen, I get the following error/warnings:
2012-12-21 16:40:05.532 python[9705:903] *** __NSAutoreleaseNoPool(): Object 0x103e25d80 of class NSCFArray autoreleased with no pool in place - just leaking
2012-12-21 16:40:05.534 python[9705:903] *** __NSAutoreleaseNoPool(): Object 0x103e26820 of class __NSFastEnumerationEnumerator autoreleased with no pool in place - just leaking
2012-12-21 16:40:05.535 python[9705:903] *** __NSAutoreleaseNoPool(): Object 0x103e9f080 of class NSObject autoreleased with no pool in place - just leaking
FWIW, one way to produce these results is shown below; all the steps shown (including the call to ipython) are taken from a matplotlib tutorial:
% ipython
...
In [1]: import matplotlib.pyplot as plt
In [2]: plt.plot([1, 3, 2, 4])
Out[3]: [<matplotlib.lines.Line2D at 0x106aabd90>]
In [3]: plt.show()
ALso, FWIW, I've observed exactly the same behavior with multiple styles of installation (on the same machine) of python+numpy+matplotlib+ipython, including installs that use the system-supplied python, those that use the python installed by homebrew, or those that use a python installed directly from source into a location off my home directory.
Any ideas of what may be going on, or what I could do about it?
I am having the same problem, one solution I found is to add the line:
plt.ion()
before the first plotting command. This turns on the interactive plotting mode and the error messages go away. This has only worked for me when plotting on the command line, if I do ion() and then show() in a script the plots don't show up at all, and if I leave the ion() out, I can see my plots, but I get the error messages. This has only happened since updated to version 1.2.0.
It's trying to do something with Cocoa, but Cocoa hasn't really been initialized or anything. You may be able to silence the errors and fix the problems by running this before:
from Foundation import NSAutoreleasePool
pool = NSAutoreleasePool()
And this after:
from AppKit import NSApplication
NSApplication.sharedApplication().run()
This requires PyObjC. Unfortunately, this may only allow for displaying one plot per IPython session. You may wish to try the IPython notebook instead, which removes the dependency on Cocoa.

Code-Completion for e.g. Numpy, SciPy or Matplotlib does not work in Eclipse PyDev

Can't get code-completion to work for e.g. SciPy, Numpy or Matplotlib in Eclipse/PyDev under Ubuntu 12.4 or 11.4. Tried with Eclipse Helios and Juno, PyDev in latest version (2.6).
Code completion does work for e.g. internal project references or builtins.
Have added path to "Preferences->Pydev->Interpreter - Python->Libraries" and added scipy, numpy and matplotlib to the "Forced Builtins". Under "Preferences->PyDev->Editor->Code Completion" "Minimum Number of chars..." is set to 1, "Preferences->PyDev->Editor->Code Completion (ctx insensitive and tokens)" "Number of chars for..." are both set to 2.
Importing and code completion works within ipython shell, so I think it must be something in PyDev...
Example code:
import numpy as np
myArr = np.array([1,2,3])
myArr.set#<hit CTRL-SPACE for completion>
Code-completion does not suggest any of the array methods here (setasflat, setfield, setflags).
Thanks for any suggestions... :)
Regards,
Carsten
I think this happens because pydev couldn't figure out what type is returned by the np.array method. If your code is long and you want code completion many times, perhaps you could "tell" pydev what is myArr's type. Try using assert:
import numpy as np
myArr = np.array([1,2,3])
assert isinstance(myArr, np.ndarray)
myArr.set#<hit CTRL-SPACE for completion>
After that code completion will always work for the myArr variable. Later you can delete or comment the assert line or use the "-O" flag with the python interpreter. Look at this page.
Just to note, in the latest PyDev version you can now let PyDev know about the type through documentation (without needing the assert isinstance).
See: http://pydev.org/manual_adv_type_hints.html for details.

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