0
0
SciPydata~5 mins

UnivariateSpline in SciPy

Choose your learning style9 modes available
Introduction

UnivariateSpline helps you draw a smooth curve through your data points. It makes it easy to see trends and patterns in noisy data.

You have scattered data points and want a smooth line to understand the trend.
You want to estimate values between known data points smoothly.
You want to reduce noise in your data while keeping the main shape.
You need a simple way to interpolate data for visualization or analysis.
Syntax
SciPy
from scipy.interpolate import UnivariateSpline
spline = UnivariateSpline(x, y, s=smoothness)

x and y are your data points as arrays.

s controls smoothness: smaller means closer to data, larger means smoother curve.

Examples
Create a spline that fits the sine values exactly (default smoothness).
SciPy
from scipy.interpolate import UnivariateSpline
import numpy as np

x = np.linspace(0, 10, 10)
y = np.sin(x)
spline = UnivariateSpline(x, y)
Use a small smoothing factor to allow some smoothing but keep close to data.
SciPy
spline = UnivariateSpline(x, y, s=1)
Use a larger smoothing factor for a smoother curve that ignores small fluctuations.
SciPy
spline = UnivariateSpline(x, y, s=10)
Sample Program

This code creates noisy sine data, fits a smooth spline, and prints smoothed values at three points.

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

# Create noisy data
x = np.linspace(0, 10, 20)
y = np.sin(x) + np.random.normal(0, 0.2, x.size)

# Create spline with smoothing
spline = UnivariateSpline(x, y, s=1)

# Generate smooth x values for plotting
x_smooth = np.linspace(0, 10, 200)
y_smooth = spline(x_smooth)

# Print some smoothed values
print('Smoothed values at x=2, 5, 8:')
for val in [2, 5, 8]:
    print(f'x={val}: y={spline(val):.3f}')
OutputSuccess
Important Notes

If s=0, the spline will pass through all points exactly (no smoothing).

Choose s based on how noisy your data is and how smooth you want the curve.

You can use the spline object to find derivatives or integrals of the smooth curve.

Summary

UnivariateSpline fits a smooth curve through 1D data points.

Use the s parameter to control smoothness.

It helps see trends and estimate values between points smoothly.