I try to use MatPlotLib and I have realized that can import it in two different ways and in both cases it works (in the same way): import pylab as p or import matplotlib.pyplot as p.
So, my question is what is the difference between these two ways?
From the official documentation:
Pylab combines the pyplot functionality (for plotting) with the numpy
functionality (for mathematics and for working with arrays) in a
single namespace, making that namespace (or environment) even more
MATLAB-like. For example, one can call the sin and cos functions just
like you could in MATLAB, as well as having all the features of
pyplot.
Note that pylab only imports from the top numpy namespace. Therefore, this will worK
import numpy
numpy.array # works
numpy.distutils # finds a module
And this will not
import pylab
pylab.array # works, is actually numpy array
pylab.distutils # gives an error
Related
I have to package libraries into distributions and I was wondering whether there was any difference between importing all the functions from the numpy modules
from numpy import pi, cos, sin, tan, arcsin, arctan, arctan2, exp, sqrt, array, polyval, polyfit, ndarray
from numpy import linspace, rad2deg, zeros, argmax, argmin, log, max, min, mean, loadtxt, delete
from numpy import float as nfloat
from numpy import append as nappend
from numpy import max as nmax
from numpy import min as nmin
from numpy.linalg import norm
or just doing the most commong way
import numpy as np
and then calling each function as
np.functionname
Someone told me that when installing the library, in the package, only the effectively used functions will appeare. But still, even if true, it is not clear to me which kind of advantage should bring.
What do you think?
Tnx!
The difference in my opinion is, that the code may be more readable. That in itself is an advantage. The header may be very clustered with imports, but your code can be more easily read. By others and yourself.
I am a Python beginner. I am trying to detrend a time-series before running an autocorrelation analysis by using acorr in matplotlib. But there is something about the syntax that I fail understand.
Matplotlib's website (https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.pyplot.acorr.html) describes how to use detrending with the acorr function: "x is detrended by the detrend callable. This must be a function x = detrend(x) accepting and returning an numpy.array." I must be reading this wrong, because the code I use does not work.
Failed attempts:
plt.acorr(values, detrend=True)
plt.acorr(values, detrend="linear")
plt.acorr(values=detrend(values))
As you can see, some rudimentary fact about syntax or matplotlib escapes me. Please help.
In matplotlib.mlab you find functions which you can use for detrending. An example:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import mlab
wn = np.random.normal(size=10**3)
plt.figure()
plt.acorr(np.abs(wn), maxlags=200, detrend=mlab.detrend_none) #default detrend
plt.figure()
plt.acorr(np.abs(wn), maxlags=200, detrend=mlab.detrend) #subtract sample mean
i used wavelet decomposition command in python using pywt library but it does not return any coefficients. my code is given below .
import numpy as np
import pywt as pywt
(e,f)=pywt.wavedec(y,'db12' ,level=2)
print("e:"+str(e))
print("f:"+str(f))
I also tried with pywt.dwt(y,' db12', level=2) it is also not returning any coefficients
it returns a null output, where y is a matrix contains my input
I tried reproducing your results with a random (discrete) signal like so:
import numpy as np
import pyw
x = np.random.randint(0,100,500)
y = pywt.wavedec(x, 'db12', level=2)
(e,f) = pywt.dwt(x, 'db12')
I noticed two things: For a 1D signal, wavedec returns more than two coefficient arrays, as also mentioned in the docs. Similarly, the dwt function does not know the keyword level=, but works just fine with the command specified above.
Hope that helps
This question already has answers here:
Python import functions from module twice with different internal imports
(3 answers)
Closed 4 years ago.
I am using numpy in one of my libraries. No surprise there.
One user would essentially like a copy of my project where I don't use the default numpy, but the one bundled with autograd. For instance, let's say I have a dumb function:
import numpy
def doSomething(x):
return numpy.sin(x)
They would like a copy of the library where all of these import numpy are replaced by from autograd import numpy:
from autograd import numpy
def doSomething(x):
return numpy.sin(x)
This would allow them to easily compute gradients and jacobians of my functions.
I would like to know what the easiest way to handle this is without copying the whole codebase and replacing all of these lines.
Options I am aware of:
I could make a copy of the codebase (lib and lib_autograd) where the first uses import numpy, and the second uses from autograd import numpy. This is bad because then I have to maintain two codebases.
I could automatically import from autograd if it is available:
try:
from autograd import numpy
except ImportError:
import numpy
The reason I do not want to do this is that many people have highly optimized numpy installs, whereas autograd might not. So I want to give the user an option which version to import. Forcing the user to use the autograd version if they have it seems bad since it would not be apparent to the user what is going on, and would require the user to uninstall autograd if they want to use the library with their default numpy installation.
So what are my options?
Ideally there would be a way of doing something like passing a parameter to the import statement (I do realize that you can't do this):
useAutograd = False
from lib(useAutograd) import doSomething
You can have 'conditional' import with:
try:
from autograd import numpy
except ImportError:
import numpy
One of other options is to have environment variable that switches whether you want to use numpy from autograd or regular one, because here you either use autograd.numpy (if it exists) or numpy. You don't have an option to use numpy if there is autograd module/package.
To elaborate on giving user an option to switch, here is one possibility:
import os
if os.environ.get('AUTOGRADNUMPY'):
try:
from autograd import numpy
except ImportError:
import numpy
else:
import numpy
Having environment variable AUTOGRADNUMPY set to True (or anything else that is not empty string) when you want to load numpy from autograd package. If it is not set or doesn't exist, regular numpy is imported.
All of this stands if user has at least numpy installed.
This might help:
try:
from autograd import numpy as np
except ImportError:
import numpy as np
...
...
np.sum(..)
I have a script which generates a series of time dependent plots. I'd like to "stitch" these together to make a movie.
I would preferably like to use matplotlib.animation. I have looked at examples from matplotlib documentation but I can't understand how it works.
My script currently makes 20 plots at successive time values and saves these as 00001.png up to 000020.png:
from scipy.integrate import odeint
from numpy import *
from math import cos
import pylab
omega=1.4
delta=0.1
F=0.35
def f(initial,t):
x,v=initial
xdot=v
vdot=x-x**3-delta*v-F*cos(omega*t)
return array([xdot,vdot])
T=2*pi/omega
nperiods = 100
totalsteps= 1000
small=int((totalsteps)/nperiods)
ntransients= 10
initial=[-1,0]
kArray= linspace(0,1,20)
for g in range (0,20):
k=kArray[g]
x,v=initial
xpc=[]
vpc=[]
if k==0:
x,v=x,v
else:
for i in range(1,nperiods)
x,v=odeint(f,[x,v],linspace(0,k*T,small))[-1] )
for i in range (1,nperiods):
x,v=odeint(f,[x,v],linspace(k*T,T+k*T,small))[-1]
xpc.append(x)
vpc.append(v)
xpc=xpc[ntransients:]
vpc=vpc[ntransients:]
pylab.figure(17.8,10)
pylab.scatter(xpc,vpc,color='red',s=0.2)
pylab.ylim([-1.5,1.5])
pylab.xlim([-2,2])
pylab.savefig('0000{0}.png'.format(g), dpi=200)
I'd appreciate any help. Thank you.
I think matplotlib.animation.FuncAnimation is what you're looking for. Basically, it repeatedly calls a defined function, passing in (optional) arguments as needed. This is exactly what you're already doing in your for g in range(0,20): code. You can also define an init function to get things set up. Check out the base class matplotlib.animation.Animation for more info on formats, saving, the MovieWriter class, etc.