Error ImportError: No module named 'np_plots' - python

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.

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 :)

Pycharm numpy module has no attribute 'py'

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:

Python ggplot and ggplotly

Former R user, I used to combine extensively ggplot and plot_ly libraries via the ggplotly() function to display data.
Newly arrived in Python, I see that the ggplot library is available, but cant find anything on a simple combination with plotly for graphical reactive displays.
What I would look for is something like :
from ggplot import*
import numpy as np
import pandas as pd
a = pd.DataFrame({'grid': np.arange(-4, 4),
'test_data': np.random.random_integers(0, 10,8)})
p2 = ggplot(a, aes(x = 'grid', y = 'test_data'))+geom_line()
p2
ggplotly(p2)
Where the last line would launch a classic plotly dynamic viewer with all the great functionalities of mouse graphical interactions, curves selections and so on...
Thanks for your help :),
Guillaume
This open plotnine issue describes a similar enhancement request.
Currently the mpl_to_plotly function seems to work sometimes (for some geoms?), but not consistently. The following code, seems to work ok.
from plotnine import *
from plotly.tools import mpl_to_plotly as ggplotly
import numpy as np
import pandas as pd
a = pd.DataFrame({'grid': np.arange(-4, 4),
'test_data': np.random.randint(0, 10,8)})
p2 = ggplot(a, aes(x = 'grid', y = 'test_data')) + geom_point()
ggplotly(p2.draw())
You don't need ggplotly in python if all you are seeking is an interactive interface.
ggplot (or at least plotnine, which is the implementation that I am using) uses matplotlib which is already interactive, unlike the R ggplot2 package that requires plotly on top.

NameError: global name 'imshow' is not defined but Matplotlib is imported

I'm currently writing a python script which plots a numpy matrix containing some data (which I'm not having any difficulty computing). For complicated reasons having to do with how I'm creating that data, I have to go through terminal. I've done problems like this a million times in Spyder using imshow(). So, I thought I'd try to do the same in terminal. Here's my code:
from numpy import *
from matplotlib import *
def make_picture():
f = open("DATA2.txt")
arr = zeros((200, 200))
l = f.readlines()
for i in l:
j = i[:-1]
k = j.split(" ")
arr[int(k[0])][int(k[1])] = float(k[2])
f.close()
imshow(arr)
make_picture()
Suffice it to say, the array stuff works just fine. I've tested it, and it extracts the data perfectly well. So, I've got this 200 by 200 array of numbers floating around my RAM and I'd like to display it. When I run this code in Spyder, I get exactly what I expected. However, when I run this code in Terminal, I get an error message:
Traceback (most recent call last):
File "DATAmine.py", line 15, in <module>
make_picture()
File "DATAmine.py", line 13, in make_picture
imshow(arr)
NameError: global name 'imshow' is not defined
(My program's called DATAmine.py) What's the deal here? Is there something else I should be importing? I know I had to configure my Spyder paths, so I wonder if I don't have access to those paths or something. Any suggestions would be greatly appreciated. Thanks!
P.S. Perhaps I should mention I'm using Ubuntu. Don't know if that's relevant.
To make your life easier you can use
from pylab import *
This will import the full pylab package, which includes matplotlib and numpy.
Cheers

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