Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smooth curved line between 3 points in plot

Tags:

python

plot

bokeh

I have 3 data points on the x axis and 3 on the y axis:

x = [1,3,5]
y=[0,5,0]

I would like a curved line that starts at (1,0), goes to the highest point at (3,5) and then finishes at (5,0)

I think I need to use interpolation, but unsure how. If I use spline from scipy like this:

import bokeh.plotting as bk
from scipy.interpolate import spline
p = bk.figure()
xvals=np.linspace(1, 5, 10)
y_smooth = spline(x,y,xvals)
p.line(xvals, y_smooth)

bk.show(p)

I get the highest point before (3,5) and it looks unbalanced: enter image description here

like image 662
Claudiu Creanga Avatar asked Aug 30 '25 17:08

Claudiu Creanga


1 Answers

The issue is due to that spline with no extra argument is of order 3. That means that you do not have points/equations enough to get a spline curve (which manifests itself as a warning of an ill-conditioned matrix). You need to apply a spline of lower order, such as a cubic spline, which is of order 2:

import bokeh.plotting as bk
from scipy.interpolate import spline
p = bk.figure()
xvals=np.linspace(1, 5, 10)
y_smooth = spline(x,y,xvals, order=2) # This fixes your immediate problem
p.line(xvals, y_smooth)

bk.show(p)

In addition, spline is deprecated in SciPy, so you should preferably not use it, even if it is possible. A better solution is to use the CubicSpline class:

import bokeh.plotting as bk
from scipy.interpolate import CubicSpline
p = bk.figure()
xvals=np.linspace(1, 5, 10)
spl = CubicSpline(x, y) # First generate spline function
y_smooth = spl(xvals) # then evalute for your interpolated points
p.line(xvals, y_smooth)

bk.show(p)

Just to show the difference (using pyplot):

enter image description here

As can be seen, the CubicSpline is identical to the spline of order=2

like image 65
JohanL Avatar answered Sep 02 '25 07:09

JohanL