0
0
SciPydata~5 mins

Spline interpolation in SciPy

Choose your learning style9 modes available
Introduction

Spline interpolation helps us draw a smooth curve through points. It fills gaps nicely when we have some data points but want to estimate values in between.

You have temperature readings every hour but want to estimate temperature every 10 minutes.
You want to smooth noisy data points from a sensor to see a clear trend.
You have a few points on a map and want a smooth path connecting them.
You want to create smooth animations by estimating positions between key frames.
Syntax
SciPy
from scipy.interpolate import make_interp_spline

spline = make_interp_spline(x, y, k=3)
y_smooth = spline(x_new)

x and y are your original data points.

k is the degree of the spline (3 means cubic spline, which is common).

Examples
This example creates a smooth curve through 4 points and finds values at points in between.
SciPy
from scipy.interpolate import make_interp_spline

x = [0, 1, 2, 3]
y = [0, 1, 0, 1]
spline = make_interp_spline(x, y, k=3)
x_new = [0, 0.5, 1, 1.5, 2, 2.5, 3]
y_new = spline(x_new)
print(y_new)
Here we use numpy arrays and create a smooth sine curve with more points.
SciPy
import numpy as np
from scipy.interpolate import make_interp_spline

x = np.linspace(0, 10, 5)
y = np.sin(x)
spline = make_interp_spline(x, y)
x_new = np.linspace(0, 10, 50)
y_new = spline(x_new)
print(y_new[:5])
Sample Program

This program shows how to use spline interpolation to draw a smooth curve through some points. It plots the original points in red and the smooth curve in blue.

SciPy
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import make_interp_spline

# Original data points
x = np.array([0, 1, 2, 3, 4, 5])
y = np.array([0, 0.8, 0.9, 0.1, -0.8, -1])

# Create spline of degree 3 (cubic)
spline = make_interp_spline(x, y, k=3)

# New x values for smooth curve
x_smooth = np.linspace(x.min(), x.max(), 100)

# Calculate smooth y values
y_smooth = spline(x_smooth)

# Plot original points and smooth curve
plt.scatter(x, y, color='red', label='Original points')
plt.plot(x_smooth, y_smooth, color='blue', label='Spline interpolation')
plt.legend()
plt.title('Spline Interpolation Example')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
OutputSuccess
Important Notes

Spline interpolation creates smooth curves that pass through all original points.

Choosing k=3 gives a smooth cubic spline, which is common and looks natural.

Make sure your x values are sorted and unique for the spline to work correctly.

Summary

Spline interpolation helps estimate values smoothly between known points.

Use make_interp_spline from scipy.interpolate to create splines.

It is useful for smoothing data and filling gaps in measurements.