only length-1 arrays can be converted to Python scalars - python

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.

Related

TypeError: only size-1 arrays can be converted to Python scalars Numpy

I have this code :
import matplotlib.pyplot as plt
import numpy as np
import math
x = np.linspace(-3,3,100)
y = math.sin(x**2) + 1.1 - ((math.e)**-x)
plt.plot(x,y,label='y = x**2')
plt.title('sin(x^2) + 1.1 - e^-x')
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.grid(alpha=.4,linestyle='--')
plt.show()
and I get this error:
TypeError: only size-1 arrays can be converted to Python scalars
Can someone help me in finding what the problem is?
I believe the problem is that you're trying to apply Python operations (specifically, math.sin) to an array, namely a NumPy array of type np.ndarray. NumPy actually has a workaround for this by implementing functions that apply the same fundamental operations element-wise, i.e. you'll want to replace the line:
y = math.sin(x**2) + 1.1 - ((math.e)**-x)
With the following:
y = np.sin(x**2) + 1.1 - (np.exp(-x))
That fixed the issue you were facing.
In general, when working with numpy, you'll want to carry out these kinds of substitutions. However, it is important to note that numpy can apply broadcasting rules (i.e. understand how to apply scalar operations to np.ndarray objects in an element-wise fashion) to the following operations:
+ (addition)
- (subtraction)
* (multiplication)
/ (division)
// (integer division)
** (exponentiate)

Using np.ravel to specify yerr in errorbar plot

My code generates values and corresponding standard deviations in sets of 3, i.e. 3x1 arrays. I want to plot them all together as a categorical errorbar plot. For specifying the yerr, since it only accepts scalar or (N,) or N x 2, I used np.ravel to convert all the 3x1 arrays to one single N x 1 array. But I still get the error ValueError: err must be [ scalar | N, Nx1 or 2xN array-like ]
Here is the code:
import numpy as np
import matplotlib.pyplot as plt
names_p=['p1','p1','p1','p2','p2','p2','p3','p3','p3','p4','p4','p4','p5','p5','p5','p6','p6','p6'] #### The names are repeated three times because for each variable I have three values
y=(p1sdm2N_ratem,p2sdm2N_ratem,p3sdm2N_ratem,p4sdm2N_ratem,p5sdm2N_ratem,p6sdm2N_ratem) #### each of these 6 elements is 3 x 1 E.g. p1sdm2N_ratem=(0.04,0.02,0.03)
c=np.ravel((p1sdm2N_ratestd,p2sdm2N_ratestd,p3sdm2N_ratestd,p4sdm2N_ratestd,p5sdm2N_ratestd,p6sdm2N_ratestd)) ### each of these 6 elements is 3x1 e.g. p1sdm2N_ratestd=(0.001,0.003,0.001)
plt. errorbar(names_p,y,yerr=c)
This gives the error I mentioned before, even though c is an 18x1 array. (It's not an array of an array, I checked.)
Note, with the way I've set up my variables,
plt.scatter(names_p,y)
and
plt. errorbar(names_p,y,yerr=None)
work, but without the errorbars, of course.
I'd appreciate any help!

How can I plot a differential equation in python?

I want to plot the solution of my differential equation but I got this:
'ValueError: x and y must have same first dimension, but have shapes
(360,) and (1,)'
When I write _plt.plot(t,final[:1])_ I got
'Equality object is not subscriptable'
statement.
Here is my code:
import numpy as np
import matplotlib.pyplot as plt
from sympy.abc import *
import sympy as sy
L= float(input('L:'))
R= float(input('R:'))
v=220*sy.sqrt(2)
i=sy.Function('i')
q=sy.dsolve(sy.Eq(sy.Derivative(i(t)*L,t)+i(t)*R,v*sy.sin(t)),i(t)).evalf()
constant=sy.solve(q.subs(i(t),0),dict=True)
t=np.linspace(0,360,360)
final=q.subs(constant[0]).evalf()
plt.plot(t,final)
plt.show()
What should I do?
It's obvious from the code that t has 360 elements
t=np.linspace(0,360,360)
The error complains that final has an initial dimension of 1, where as it should be 360 like t. While it is possible the final has (1,) shape (1 element, containing another array or list), more likely it is (1, n).
When you get shape errors, you need to look at the shape of relevant arrays,
print(final.shape, final.dtype)
and decide from that the correct way of adjusting the shapes.
plot can handle a second argument that is (360,m), where m is the number of lines that it should plot.

Data Visulization : Matplotlib and Numpy throwing value error

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.

Python array values differ from defined function

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.

Categories