1

I would like to display the smoothed curve between two lists.
The two lists have values that they correspond to different values on the other list. The values of the two lists are linked by their indices. Of course the size of the two lists is identical.

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

list1 = [0.9117647058823529, 0.9117647058823529, 0.9090909090909091,..]
list2 = [0.32978723404255317, 0.34065934065934067, 0.3448275862068966,..]

#plt.plot(list1, list2) works well

x = np.array(list1)
y = np.array(list2)

xnew = np.linspace(x.min(), x.max(), 300) 
spl = make_interp_spline(x, y)
y_smooth = spl(xnew)
plt.plot(xnew, y_smooth)

gives me ValueError: Expect x to be a 1-D sorted array_like.

When I use interp1d rather than make_interp_spline I have ValueError: Expect x to not have duplicates

How to display the smoothed curve without losing any point? Thank you for your attention.

Tim
  • 513
  • 5
  • 20

1 Answers1

1

You can parameterize a curve represented by the x/y values with a parameter (called param in the code below) that goes from 0 to 1 (or any other arbitary range), compute the coefficients of the interpolating spline and then interpolate the curve again using a finer spacing of the parameter.

param = np.linspace(0, 1, x.size)
spl = make_interp_spline(param, np.c_[x,y], k=2) #(1)
xnew, y_smooth = spl(np.linspace(0, 1, x.size * 100)).T #(2)
plt.plot(xnew, y_smooth)
plt.scatter(x, y, c="r")

Remarks:

  1. The degree of the spline can be chosen to be greater than 2 if there are more than three datapoints available. The default would be k=3.

  2. 100 controls the amount of interpolated points for the new curve. If x becomes larger, a smaller number could be used here.

Result:

spline

werner
  • 13,518
  • 6
  • 30
  • 45
  • Thank you very much @werner for the answer and the explanations! I've been thinking about it and I would like to go further, is it possible to force the smoothing on the curve? I have edited the question. – Tim Jun 24 '21 at 23:18
  • 1
    @Tim in your original question you asked how to plot the curve _without losing any point_. The second thing you are asking now is quite different from that, because now you expect the curve not to contain all of the points. I would suggest you leave your original question unchanged and ask a new question, as a spline will probably not the best approach for the changed question. With a new question you will also increase the chances of attracting other answerers with good ideas! – werner Jun 25 '21 at 16:19