Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to interpolate points in a specific interval on a plot formed by loading a txt file in to scipy program?

I have a text file with two columns, x and y. I have plotted them using the below program 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 increment of around 0.1 on the same graph?

like image 428
avinash Avatar asked Feb 16 '23 18:02

avinash


1 Answers

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 the univariatespline, just replace the f = interpolate... line with:

f = interpolate.UnivariateSpline(x, y)

To change how much it smooths, you can fiddle with the s and k options:

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

As described at the documentation

like image 98
askewchan Avatar answered Feb 19 '23 10:02

askewchan