Module matplotlib.cm has no [color] member - python

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",
]

Related

qiskit plots not showing up in spyder console

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.

PyCharm - Auto Completion for matplotlib (and other imported modules)

I am using PyCharm 2016.1 and Python 2.7 on Windows 10 and imported the matplotlib module.
As the matplotlib module ist very extensive and I am relatively new to Python, I hoped the Auto Complete function in PyCharm could help me to get an overview of the existent properties/ functions of an object. It would be more convenient as digging through the api documentation every time, not knowing what to look for an where to find it.
For example:
from matplotlib import pyplot as plt
fig, ax = plt.subplots()
When I type ax. there ist no auto completion for the properties, functions etc. of the axis, I only get the suggestions list.
I already tried this and imported the axis module directly with:
import matplotlib.axis as axis
or
from matplotlib.axis import Axis as axis
Smart Auto Completion and 'Collect run-time types information' is already enabled.
Is there a way to enable the auto completion like described or is there another IDE that supports that?
I believe your problem is highlighted here:
https://intellij-support.jetbrains.com/hc/en-us/community/posts/205816499-Improving-collecting-run-time-type-information-for-code-insight?sort_by=votes
Tldr return types can vary, so it cant be figured out at compile time.
Most accepted way is to use a type hint, since it can only figure out what type it as run time :
import matplotlib.axes._axes as axes
fig = plt.figure(figsize=(5,10))
ax1 = fig.add_subplot(3,1,1) # type:axes.Axes
ax1.set_xlabel('Test') <- now autocompletes
You can also try an assert isinstance:
import matplotlib.axes._axes as axes
fig = plt.figure(figsize=(5,10))
ax1 = fig.add_subplot(3,1,1)
assert isinstance(ax1, axes.Axes)
ax1.set_xlabel('Test')
It wont find the autocomplete if you do it after the method you are looking for:
ax1.set_xlabel('Test')
assert isinstance(ax1, axes.Axes)
With this, you shouldnt let isinstance dictate the control flow of your code, if you are trying to run a method that doesnt exist on an object, it should crash, however, if your different object has a method of the same name (!) then you have inadvertently reached that goal without annotations being there. So I like it better, since you want it to crash early and in the correct place. YMMV
From the doc:
Assertions should not be used to test for failure cases that can
occur because of bad user input or operating system/environment
failures, such as a file not being found. Instead, you should raise an
exception, or print an error message, or whatever is appropriate. One
important reason why assertions should only be used for self-tests of
the program is that assertions can be disabled at compile time.
If Python is started with the -O option, then assertions will be
stripped out and not evaluated. So if code uses assertions heavily,
but is performance-critical, then there is a system for turning them
off in release builds. (But don't do this unless it's really
necessary.
https://wiki.python.org/moin/UsingAssertionsEffectively
Alternatively, if you dont want to add to your code in this fashion, and have Ipython/jupyter installed through anoconda, you can get the code completion from the console by right clicking the code to be ran and choosing "execute selection in console"
In addition to Paul's answer. If you are using fig, ax = plt.subplots() , you could use figure type hint. See below example:
from matplotlib import pyplot as plt
import matplotlib.axes._axes as axes
import matplotlib.figure as figure
fig, ax = plt.subplots() # type:figure.Figure, axes.Axes
ax.
fig.

Hold is not working for pyplot

I have a problem using pyplot. I am new to Python so sorry if I am doing some obvious mistake.
After I have plotted something using pyplot it shows the graph, but when I then try and add e.g. ylabel it will not update the current graph. It results in a new graph with only the ylabel, not previously entered information. So to me it seems to be a problem with recognizing the current graph/axis, but the ishold delivers a True statement.
My setup is Python 2.7 in Python(x,y). The problem occurs both in the Spyder IDE and the IPython Qt Console. It does however not occur in the regular IPython console (which, by constrast, is not interactive, but everything is included when using show(). When I turn off interactive in Spyder/Qt console it does not show anything after using the show() command).
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
Out[2]: [<matplotlib.lines.Line2D at 0x78ca370>]

plt.ylabel('test')
Out[3]: <matplotlib.text.Text at 0x5bd5990>

plt.ishold()
Out[4]: True
matplotlib.get_backend()
Out[6]: 'module://IPython.kernel.zmq.pylab.backend_inline'
Hope any of you have some input. Thanks.
This is one of the things were InlineBackend have to behave differently from other backend or you would have sort of a memory leak. You have to keep explicit handle to matplotlib figure and/or set close_figure to False in config. Usually pyplot is a compatibility layer for matlab for convenience, try to learn to do using the Object Oriented way.
fig,ax = subplots()
ax.plot(range(4))
ax.set_ylabel('my label')
...

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.

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