avi*_*ash 4 python matlab interpolation numpy matplotlib
我有一个包含两列x和y的文本文件.我在scipy中使用以下程序绘制了它们,如下所示.
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()
Run Code Online (Sandbox Code Playgroud)
现在我想知道如何进行插补几个点x=1,并x=5与在同一图中大约0.1%的增量?
您可以使用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()
Run Code Online (Sandbox Code Playgroud)
如果您想平滑数据,可以使用univariatespline,只需将f = interpolate...行替换为:
f = interpolate.UnivariateSpline(x, y)
Run Code Online (Sandbox Code Playgroud)
要改变多少平滑,可以用小提琴s和k选项:
f = interpolate.UnivariateSpline(x, y, k=3, s=1)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3451 次 |
| 最近记录: |