clm42
clm42

Reputation: 65

how can I overcome y array length error in scipy.interpolate.interp1d()?

I put together a function based on this example for smoothing matplotlib lines but when I try to interpolate the y data I get the error "ValueError: x and y arrays must be equal in length along interpolation axis." I assume it wants me to have an array of empty values the length of the numpy.linspace of the x data with the y data distributed correctly through it but I don't know how to do that. I don't even know if that's right.

def spline_it(key):
        y = [i[1] for i in datapoints[key]]
        x_smooth = np.linspace(0,len(y),len(y)*10)
        y_smooth = interp1d(x_smooth, y, kind='cubic')
        return x_smooth, y_smooth(x_smooth)

Upvotes: 0

Views: 1500

Answers (1)

hpaulj
hpaulj

Reputation: 231605

The 1st argument to interp1d must match the second in size. Together they define the original data, i.e. the x coordinates for the corresponding y points.

Try:

def spline_it(key):
    y = [i[1] for i in datapoints[key]]
    x = np.arange(len(y))
    interpolator = interp1d(x, y, kind='cubic')
    x_smooth = np.linspace(0,len(y),len(y)*10)
    y_smooth = interpolator(x_smooth)
    return x_smooth, y_smooth

I renamed some variables to clarify what is what.

Upvotes: 1

Related Questions