Search code examples
pythoninterpolationspline

Curve between 4 points using interpolation


I have 4 known points that I am trying to run a smooth curve through.

gg_xy=np.array([[-2.612,0],[0,1.6969999999999996],[0.5870000000000001,0],[0,-2.605]])
plt.plot(gg_xy[:,0],gg_xy[:,1],'ro')

ggx,ggy=splprep(gg_xy.T,u=None,s=0.0,per=1)
gg_xspline=np.linspace(ggy.min(),ggy.max(),300)
ggxnew,ggynew=splev(gg_xspline,ggx,der=0)
plt.plot(ggxnew,ggynew)
plt.show()

This is my ouput:Spline Plot

It is missing a point when interpolating. Could someone help me force it through this point? Is there a better way to do this other than using spline interpolation? Edit: the curve must be a single connected loop. Thanks!


Solution

  • from scipy.interpolate import splprep, splev
    import matplotlib.pyplot as plt
    import numpy as np
    
    gg_xy=np.array([[-2.612,0],[0,1.6969999999999996],
                    [0.5870000000000001,0],[0,-2.605], [0,-2.605]])
    plt.plot(gg_xy[:,0],gg_xy[:,1],'ro')
    
    ggx,ggy=splprep(gg_xy.T,u=None,s=0.0,per=1)
    gg_xspline=np.linspace(ggy.min(),ggy.max(),300)
    ggxnew,ggynew=splev(gg_xspline,ggx,der=0)
    plt.plot(ggxnew,ggynew)
    plt.show()
    

    enter image description here

    Docs:

    per: int, optional

    If non-zero, data points are considered periodic with period x[m-1] - x[0] and a smooth periodic spline approximation is returned. Values of y[m-1] and w[m-1] are not used.

    Looks like it ignores the last point, so I just repeated the last point.