Tom Kurushingal
Tom Kurushingal

Reputation: 6476

How to get correct interpolated values in SciPy?

I am using this data to obtain interpolated results using SciPy's InterpolatedUnivariateSpline but when I plot the interpolated data with original data it seems they are not correctly interpolated. I get interpolated data as shown in fig.:

plot with incorrect interpolation

How do I correctly obtain interpolated values in Python with this data?

MWE

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


data = np.loadtxt('interp.dat', delimiter = '\t')
x = data[:, 0]
y = data[:, 1:]

x_interp = np.linspace(x[0], x[-1], 301)
y_interp = np.empty(shape = (x_interp.shape[0], y.shape[1]))
for i in range(y.shape[1]):
    f = interpolate.InterpolatedUnivariateSpline(x, y[:, i], k = 3)
    y_interp[:, i] = f(x_interp)


fig = plt.figure()
plot = plt.subplot(111)
markers = itertools.cycle(('o', '^', 's', 'v', 'h', '>', 'p', '<'))
for i in range (y.shape[1]):
    plt.plot(x, y[:, i], linestyle = '', marker = markers.next())
    plt.plot(x_interp, y_interp[:, i], linestyle = ':')
plot.set_ylim([0, 200])
plot.set_ylabel('Y')
plot.set_xlabel('X')
fig.savefig('interp.pdf')

Upvotes: 1

Views: 539

Answers (1)

Frank M
Frank M

Reputation: 1570

The problem is that InterpolatedUnivariateSpline requires increasing x points, and yours are decreasing. From it's documentation:

x : (N,) array_like Input dimension of data points -- must be increasing

If you reverse your x- values with

x = data[::-1, 0]
y = data[::-1, 1:]

instead of

x = data[:, 0]
y = data[:, 1:]

it interpolates correctly. There's still something odd about the data with the highest y-values.

Thank you for posting your data; without that it would have been impossible to figure out what's wrong.enter image description here

Upvotes: 3

Related Questions