Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValueError: Expect x to be a 1-D sorted array_like.I am trying to plot smooth curve but couldn't

I got two arrays after doing some calculation in python.

first one :

**t**: [0, 1.5e-13, 3e-13, 4.5e-13, 6e-13, 7.499999999999999e-13, 8.999999999999999e-13, 1.05e-12, 1.2e-12, 1.35e-12, 1.4999999999999999e-12, 1.6499999999999998e-12, 3e-13, 4.5e-13, 6e-13, 7.499999999999999e-13, 8.999999999999999e-13, 1.05e-12, 1.2e-12, 1.35e-12, 1.4999999999999999e-12]

second one:

**X2**: [2.0000000000000003e-34, 3.953299280814115e-14, -0.16661594736661114, 363384313676.0453, 1.6249307273647528e+24, -2.606395610181476e+37, 1.9393976227227167e+50, -1.0229289218046666e+63, 3.6974904635770745e+75, -3.685245806003695e+87, -7.685163462952308e+100, 8.267305810721622e+113, -0.16661594736661114, 363384313676.0453, 1.6249307273647528e+24, -2.606395610181476e+37, 1.9393976227227167e+50, -1.0229289218046666e+63, 3.6974904635770745e+75, -3.685245806003695e+87, -7.685163462952308e+100]

My code:

     from matplotlib import pyplot as plt
     from scipy.interpolate import make_interp_spline as sp, BSpline
     x_new = np.linspace(min(t), max(t), 300)
     spl = sp(t, X2, k=3)  
     a_BSpline = sp(t, X2)
     y_new = spl(x_new)

     plt.plot(x_new,y_new)
     plt.show()

I am getting error as

ValueError: Expect x to be a 1-D sorted array_like.
like image 526
RISHAV SAGAR Avatar asked Jul 15 '20 11:07

RISHAV SAGAR


1 Answers

So as the ValueError says, you need two expressions to be true: 1-D and sorted. Which corresponds to:

if x.ndim != 1 or np.any(x[1:] <= x[:-1]):
         raise ValueError("Expect x to be a 1-D sorted array_like.")

If you check this:

t = np.array([0, 1.5e-13, 3e-13, 4.5e-13, 6e-13, 7.499999999999999e-13, 8.999999999999999e-13, 1.05e-12, 1.2e-12, 1.35e-12, 1.4999999999999999e-12, 1.6499999999999998e-12, 3e-13, 4.5e-13, 6e-13, 7.499999999999999e-13, 8.999999999999999e-13, 1.05e-12, 1.2e-12, 1.35e-12, 1.4999999999999999e-12])

print(t.ndim)
print(np.any(t[1:] <= t[:-1]))

The output will be:

1
True

Which means that your array is 1-D, but not sorted.

Your Problem is, that even if you sort your array by np.sort(), the error will still rise, because you got numbers in your array which are equal. Therefore the <= test will still be true.

I would suggest to format() your numbers so they become distinguishable.

like image 181
Jonas Avatar answered Nov 11 '22 01:11

Jonas