Pycharm numpy module has no attribute 'py' - python

Just getting into programming by going through a load of beginner projects. I started one to plot sine and cosine curves, and the code they gave was:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 4*np.py, 0.1)
y = np.sin(x)
plt.plot(x, y)
plt.show()
Every time I try and run the code, it gives the error:
Traceback (most recent call last):
File "C:/Users/Alex/PycharmProjects/projects2/sin2.py", line 5, in <module>
x = np.arange(0, 4*np.py, 0.1)
File "C:\Users\Alex\anaconda3\envs\projects2\lib\site-packages\numpy\__init__.py", line 220, in __getattr__
"{!r}".format(__name__, attr))
AttributeError: module 'numpy' has no attribute 'py'
I've reinstalled Python, pycharm, and numpy to no avail. I believe I'm properly using the anaconda interpreter and I see numpy is properly installed on it. I'm not sure what else I should try, so any suggestions would help. Maybe I should try another IDE? I do like Pycharm so far but I have seen other people with similar issues using Pycharm, so any suggestions there would also be welcome.

I think you are trying to get np.pi
The constant 3.1415926535897932384626433...
If you change it in your code:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 4 * np.pi, 0.1)
y = np.sin(x)
plt.plot(x, y)
plt.show()
It properly runs

I not very familiar with numpy, but I looked through the docs and couldn't find anything for py being part of numpy. Maybe I didn't look hard enough, but it could have been replaced with an update? Also, you could try changing it to "np.py()" with parentheses because it could just be a function instead (however that is probably not likely assuming you got this from a prebuilt project).

I don't know, why are you using 4*np.py, I have seen the documentation of NumPy and it has no such attribute as py. You can try following:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y = np.sin(x)
plt.plot(x, y)
plt.title('sine wave') # To give a title
plt.xlabel('Time') # To give a x-label
plt.ylabel('Y-values') # To give a y-label
plt.grid(True, which='both') # Turns Grid to True
plt.axhline(y=0, color='k') # Draw a black horizontal line at y=0
plt.show()
Output:

Related

Plot matplotlib by running python file

So there was this thread talking about why matplotlib does not show when executing
python myfile.py
The most popular answer was about resetting matplotlibrc file. What would need to be reset in this file?
Also, some suggest to include matplotlib.use('TkAgg') in the import. Below is my python file:
#myfile.py
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import numpy as np
def dyn_draw():
x = np.linspace(0, 6 * np.pi, 100)
y = np.sin(x)
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(x, y, 'r-') # Returns a tuple of line objects, thus the comma
for phase in np.linspace(0, 10 * np.pi, 500):
line1.set_ydata(np.sin(x + phase))
fig.canvas.draw()
fig.canvas.flush_events()
if __name__ == "__main__":
dyn_draw()
Running that with python myfile.py, I get the following error:
ImportError: Cannot load backend 'TkAgg' which requires the 'tk' interactive framework, as 'headless' is currently running
Another thread here discussed this error. But the solution still does not work (i.e. restarting the kernel).
How to plot this particular python code with the python command?
You are trying to run matplotlib interatively in a non-interactive environment. The code compiles, but errors at run-time because you running a script.
Have you tried running this in Google Colab? The resource provides free (to a certain point) GPU usage and block coding for interactive visualizations.
Best of luck :)

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

matplotlib numpy -- TypeError: Cannot read property 'props' of undefined -- Graph not showing up?

This code works on one machine, but not the other. I can't seem to isolate the issue with the dependencies.
Sample code from: https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/simple_plot.html
--
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t, s)
ax.set(xlabel='time (s)', ylabel='voltage (mV)',
title='About as simple as it gets, folks')
ax.grid()
fig.savefig("test.png")
plt.show()
--> TypeError: Cannot read property 'props' of undefined
This code does not produce a stack trace of explicitly fail. The TypeError: is returned by the call to plt.show(). I tried searching for this error, but I couldn't find anything reported. (I added a screenshot of what visual-studio on the server I am working on shows. I will likely just create a docker of my other environment as I should have done that in the first place to avoid having my configuration break.) The graph saves correctly to file. It's just an issue with plt.show().
np.version
'1.17.2'
matplotlib.version
'3.1.1'
screen-shot
graph-saves-correctly
Can you tell us on which line it fails specifically? Which function call causes the issue? You could comment everything and then uncomment every line until an error occurs on execution. Maybe there's a github page of this issue.
My suspicion is, that it's the ax.set() call. Haven't seen that before and never used it. Maybe it's deprecated in mpl 3.1.1. Apparently, this error can occur, when you pass a parameter that the function doesn't know (xlabel,ylabel,title): Uncaught TypeError: Cannot read property 'value' of undefined
As a test, try running this:
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t, s)
ax.set_ylabel('voltage (mV)')
ax.set_xlabel('time (s)')
ax.set_title('About as simple as it gets, folks')
ax.grid()
fig.savefig("test.png")
plt.show()

Error ImportError: No module named 'np_plots'

I have the next code in python
import np_plots as npp
import matplotlib.pyplot as plt
import numpy as np
import math as m
import scipy
from scipy.integrate import odeint
def plotLimitCycle(bval):
rhs = lambda X, t: [-X[0]+X[1]*X[0]**2, bval - X[1]*X[0]**2]
xeq, yeq = bval, 1.0/bval
cyclerad = m.sqrt(1-bval)
nbh = min(cyclerad, 0.05)
IC = [xeq-nbh/5.0, yeq-nbh/5.0]
time_span = np.linspace(0,400,40000)
fig = plt.figure()
solution = odeint(rhs, IC, time_span)
X, Y = zip(*solution)
plt.plot(X, Y)
axes = plt.gca()
axXmin, axXmax = axes.get_xlim()
axYmin, axYmax = axes.get_ylim()
xmin = max(-15, axXmin)
xmax = min(15, axXmax)
ymin = max(-15, axYmin)
ymax = min(15, axYmax)
X,Y,U,V = npp.ezDomainQuiver2D([[xmin, xmax],[ymin, ymax]],[25,25],lambda X: rhs(X, 0),Normalize=True)
plt.quiver(X,Y,U,V)
plt.scatter([xeq],[yeq], color='red')
plt.xlim([xmin, xmax])
plt.ylim([ymin, ymax])
plt.axes().set_aspect('equal', 'datalim')
plt.show()
It work pretty well on my friend computer because he showed me the plots but I can't make it run in mine, I'm using Python 3.5.0cr1 Shell to run it out but it always came with te next error:
**Traceback (most recent call last):
File "C:\Users\PankePünke\Desktop\limites.py", line 1, in <module>
import np_plots as npp
ImportError: No module named 'np_plots'**
I'm totally new in Python programming and my friend made this program for me in order to make some advances in my thesis but I want to continue working with this program and get the plots from this. I do not know how to install or what kind of procceddure I should follow in order to get what I want (the plots and graphics that this program make) So... I'll be very thankful if somebody can help me in not a advance way, because how a wrote I'm totally new in Python, I just installed it and that is all.
You friend had a lib called np_plots on their computer, it is not part of the standard lib so you need to also install/get it on your comp or the code will not run. Most likely your friend actually wrote the code as I cannot see any mention of that lib anywhere so you will have to get it from them.
Apart from your friends lib, scipy and numpy are also not in the standard library, they do come with some distributions like Canopy but if you just installed a regular version of python you will need to install those also.
Might be worth checking out pip as it is the de-facto standard package manager for python.

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

Categories