Search code examples
pythonpandasscipysplinecubic-spline

How do you create a cubic spline with knots in Python?


I'm trying to fit a cubic spline with three knots to some data to graph seasonality of a variable. My X data is the day number in a year (essentially range(0,366)) and the y data is the variable that is seasonal.

How do I create a cubic spline with three knots that fits to the data?

I've attempted to use:

    spline = sp.interpolate.interp1d(Xdata, ydata, kind='cubic')

And:

    spline = CubicSpline(Xdata, ydata, bc_type='periodic')

However, plotting the results from these with:

    plt.plot(range(0,366), spline(range(0,366)))

results in an exact plot of my ydata, with all the possible noise. I'm trying to create a smoothed line that is fit through the data.

My goal is to create a seasonality model that has the same y(x) value at day 0 and day 365, and a spline that bends 3 times between those values.


Solution

  • make_lsq_spline from scipy.interpolate creates a least-squares spline fit with fixed predefined knots.