4

我有一个包含两列 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()

现在我想知道如何在同一张图上以大约 0.1 的增量x=1插入几个点?x=5

4

1 回答 1

8

您可以使用以下方法创建函数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()

如果要平滑数据,可以使用univariatespline,只需将f = interpolate...行替换为:

f = interpolate.UnivariateSpline(x, y)

要更改它的平滑程度,您可以使用sk选项:

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

文档中所述

于 2013-04-17T21:11:09.843 回答