Home > Back-end >  Is there a way to smooth a line between points such that the gradient at each point is 0?
Is there a way to smooth a line between points such that the gradient at each point is 0?

Time:03-04

Is there a way to smooth this line between the points such that the line gradient at each point is 0 (as if there were a cubic function between the points, with each data-point as a turning point).

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x = [1,2,3,4,5,6,7,8,9,10]
y = [8,2,1,7,5,5,8,1,9,5]

ax.plot(x,y)

'Unsmoothed' plot:
enter image description here

CodePudding user response:

I am not sure if the use case is desirable, but you can use a spline interpolation with spline interpolation

alternative: cubic hermite spline

with threshold (only for "nice" display purposes)
import numpy as np
from scipy.interpolate import CubicHermiteSpline

g = np.gradient(y)/np.gradient(x)
g = np.where(abs(g)>2, g, 0)

cs = CubicHermiteSpline(x, y, g)

xs = np.linspace(min(x), max(x), num=100)

fig, ax = plt.subplots()
ax.plot(x, y, label='data', marker='o')
ax.plot(xs, cs(xs), label='spline')
ax.legend()

output:

custom spline

  • Related