I have defined and function and calling it to store the computed values in an array. However the values in array are different than what they should be. I have plotted both the output of the function and stored array values. Can anyone help me resolve this issue. Here is the code and the output.
from numpy import linspace, exp
import matplotlib.pyplot as pl
def gaussian(x, off, amp, cen, wid):
return off+amp * exp(-(x-cen)**2 /wid**2)
PhaseArray = [0 for x in range (100)]
for x in range(100):
PhaseArray[x] = gaussian(x, 0, 1000, 50, 15)
x = linspace(0,99,100)
fig = pl.figure()
pl.plot(PhaseArray, 'go-')
pl.plot(x, gaussian(x, 0, 1000, 50, 15), 'ro-')
pl.show()
The output plot looks like
linspace provides a vector of float numbers that go to gaussian as a vector and are processed according to numpy operators over vectors. On the other hand, to fill PhaseArray you feed gaussian by integer x that is processed in a different way. It explains the difference.
Related
I have searched long and hard and cannot find a way to do this.
x = random.normal(100,100)
This is a variable X of type float. I want to pass all the elements of the first column as X coordinates and the elements of the second column as Y coordinates to the matplotlib.pyplot function. How do I do it ?
Also how to determine the shape of a float array ? In this case it is clearly 100x100 but since float objects do not have a float.shape attribute.
Your np.random.normal(100,100) is a simple, single float...
Like so?
import matplotlib.pyplot as plt
import numpy as np
data = np.random.normal((100,100)*100) # 2 * 100 values = 200 values normalized around 100
x = data[0::2] take even as X
y = data[1::2] take uneven as Y
plt.scatter(x,y)
plt.plot(x,y)
plt.grid(True)
plt.show()
To elaborate slightly on #Patrick Artner's answer...
x = random.normal(100,100)
This generates one random variable from a normal distribution with mean = 100 and standard deviation = 100. To see the answer more clearly, you could specify keyword arguments as
x = np.random.normal(loc=100, scale=100)
Note: loc = mean and scale = standard deviation.
See numpy's documentation: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.random.normal.html
To answer your question about how to determine the shape of a float array, you simply call the .shape function on a float array. For example:
x = np.random.normal(0, 1, (100, 2))
print("The shape of x is %s" % (x.shape,))
Suppose I have a coordinate grid with a few points(masses) sprinkled in the grid. I can create this using:
import numpy as np
import matplotlib.pyplot as plt
points = np.array([[0,1],[2,1],[3,5]]) # array containing the coordinates of masses(points) in the form [x,y]
x1, y1 = zip(*points)
Now, I can plot using :
plt.plot(x1,y1,'.')
Now, say I create a 2D meshgrid using:
x = np.linspace(-10,10,10)
y = np.linspace(-10,10,10)
X,Y = np.meshgrid(x,y)
Now, what I want to do is to create a 2D array 'Z',(a map of the masses)that contains masses at the locations that are in the array points. When I mean masses, I just mean a scalar at those points. So I could do something like plt.contourf(X,Y,Z). The problem I'm having is that the indices for Z cannot be the same as the coordinates in points. There has to be some sort of conversion which I'm not able to figure out. Another way to look at it is I want:
Z[X,Y] = 1
I want Z to have 1's at locations which are specified by the array points. So the essence of the problem is how do I calculate the X and Y indices such that they correspond to x1, y1 in real coordinates.
For example, if I simply do Z[x1(i),y1(i)] = 1, contourf gives this:
Instead I want the spikes to be at (0,1),(2,1),(3,5).
To have 1 at the coordinates specified by x1, y1 and zeros everywhere else, I would write it like this:
x = np.linspace(-10, 10, 21)
y = np.linspace(-10, 10, 21)
Z = np.zeros((len(y), len(x)))
for i in range(len(x1)):
Z[10 + y1[i], 10 + x1[i]] = 1
Then you should be able to write plt.contourf(x, y, Z).
Tell me if that gives you the desired result.
I am new to machine learning. I was teaching myself data visualization with MATPLOTLIB. my code is pretty simple.
It takes a numpy array (x = np.random.rand(1,100)) of shape=(1, 100)).
It converts numpy array x into y(y = np.sin(x)).
Final task is to visualise this in a BAR(plt.bar(x, y, label="BAR", color='r'))
But it is throwing VALUE ERROR.Even though there are already answers to this question, but none seems to work so far for me.
In one answer for this question By unutbu
he explains that this error is raised "whenever one tries to evaluate an array in boolean context".
I am unable to understand how I am using these arrays as boolean?
MY CODE:
import matplotlib.pyplot as plt
import numpy as np
#arguments are shape: 1=row; 100=columns
x = np.random.rand(1, 100)
y = np.cos(x)
#bars
plt.bar(x, y, label='Bars1', color='pink')
#legends
plt.legend()
#show the figure
plt.show()
You need to replace
x = np.random.rand(1, 100)
with
x = np.random.rand(100)
The reason is that the former gives you an array of arrays (with one array inside, but it is still a 2D array overall with dimensions 1-by-100), while the latter gives you a 1D array (of length 100). In order to visualize it with plt, you need the latter.
I have a 2D numpy array that represents the coordinates (x, y) of a curve, and I want to split that curve into parts of the same length, obtaining the coordinates of the division points.
The most easy example is a line defined for two points, for example [[0,0],[1,1]], and if I want to split it in two parts the result would be [0.5,0.5], and for three parts [[0.33,0.33],[0.67,0.67]] and so on.
How can I do that in a large array where the data is less simple? I'm trying to split the array by its length but the results aren't good.
If I understand well, what you want is a simple interpolation. For that, you can use scipy.interpolate (http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html):
from scipy.interpolate import interp1d
f = interp1d(x, y) ## for linear interpolation
f2 = interp1d(x, y, kind='cubic') ## for cubic interpolation
xnew = np.linspace(x.min(), x.max(), num=41, endpoint=False)
ynew = f(xnew) ## or f2(xnew) for cubic interpolation
You can create a function that returns the coordinates of the split points, given x, y and the number of desired points:
def split_curve(x, y, npts):
from scipy.interpolate import interp1d
f = interp1d(x, y)
xnew = np.linspace(x.min(), x.max(), num=npts, endpoint=False)
ynew = f(xnew)
return zip(xnew[1:], ynew[1:])
For example,
split_curve(np.array([0, 1]), np.array([0, 1]), 2) ## returns [(0.5, 0.5)]
split_curve(np.array([0, 1]), np.array([0, 1]), 3) ## [(0.33333333333333331, 0.33333333333333331), (0.66666666666666663, 0.66666666666666663)]
Note that x and y are numpy arrays and not lists.
take the length of the line on every axes, the split as you want.
example:
point 1: [0,0]
point 2: [1,1]
then:
length of the line on X axes: 1-0 = 1
also in the Y axes.
now, if you want to split it in two, just divide these lengths, and create a new array.
[0,0],[.5,.5],[1,1]
How I can change that code for running? It is necessary to run graphic that produces a function w(omega) = 1/(1 + 1j*omega) on the real and imaginary axis.
import matplotlib.pyplot as plt
import numpy as np
def func(a):
for x in range(len(a)):
plt.plot([0, a[x].real], [0, a[x].imag], 'ro-', label='python')
limit=np.max(np.ceil(np.absolute(a))) # set limits for axis
plt.xlim((-limit,limit))
plt.ylim((-limit,limit))
plt.ylabel('Imaginary')
plt.xlabel('Real')
plt.show()
omega = np.linspace(-4, 4, 251)
a = np.arange(1) + 1j*np.arange(omega, 1)
func(a)
To answer your specific question: the error arises from the fact that omega is an array, but arange expects scalar arguments: the from-to-step values. Since it gets a length-1 array (omega), it can't determine which value of omega it should choose as the starting point of the range. Hence the error: omega cannot be converted to a scalar (which would make arange work).
But it's still unclear why you're exactly plotting this way, and exactly what you want to put in the array a.