How to interpolate points in a certain interval on a section formed by loading a txt file into a scipy program?

I have a text file with two columns, x and y. I built them using the program below in scipy, as shown below.

import matplotlib.pyplot as plt with open("data.txt") as f: data = f.read() data = data.split('\n') x = [row.split(' ')[0] for row in data] y = [row.split(' ')[1] for row in data] fig = plt.figure() ax1 = fig.add_subplot(111) ax1.set_title("Plot B vs H") ax1.set_xlabel('B') ax1.set_ylabel('H') ax1.plot(x,y, c='r', label='the data') leg = ax1.legend() plt.show() 

Now I would like to know how to interpolate several points between x=1 and x=5 with an increment of about 0.1 on the same graph?

+4
source share
1 answer

You can create a function using scipy.interp1d :

 import numpy as np from scipy import interpolate data = np.genfromtxt('data.txt') x = data[:,0] #first column y = data[:,1] #second column f = interpolate.interp1d(x, y) xnew = np.arange(1, 5.1, 0.1) # this could be over the entire range, depending on what your data is ynew = f(xnew) # use interpolation function returned by `interp1d` fig = plt.figure() ax1 = fig.add_subplot(111) ax1.set_title("Plot B vs H") ax1.set_xlabel('B') ax1.set_ylabel('H') ax1.plot(x,y, c='r', label='the data') ax1.plot(xnew, ynew, 'o', label='the interpolation') leg = ax1.legend() plt.show() 

If you want to smooth your data, you can use univariatespline , just replace the line f = interpolate... with:

 f = interpolate.UnivariateSpline(x, y) 

To change how smooth it is, you can play with the s and k parameters:

 f = interpolate.UnivariateSpline(x, y, k=3, s=1) 

As described in the documentation

+8
source

All Articles