使用matplotlib绘制的数据的外推方法
我在文件里有10个x和y的值。
有没有办法可以把这个图表延伸出去,也就是把它变成一个连续的函数,并且可以增加其他x值的范围,使用matplotlib这个工具?
如果有人能告诉我有没有其他软件可以用,我也会很感激。我基本上想要的是把这10个值近似成一个连续的函数,这样我就可以知道在某个随机的x点对应的y值。
2 个回答
5
如果你在使用 SciPy
(科学计算的Python库),可以试试 scipy.interp1d
这个功能。想了解怎么用,可以看看这个 手册,里面有例子。
如果没有这个库,任何好用的电子表格软件也应该能做样条插值,帮你画出平滑的图表。
不过要小心 外推。如果你对数据没有一个好的模型,外推到输入范围之外时,可能会得到完全不相关的数据。
例子(编辑):
from scipy.interpolate import interp1d
# the available data points
x = [1, 2, 3]
y = [10, 20, 30]
# return a function f, such that f(x) is the interpolated value at 'x'
f = interp1d(x, y, kind='cubic')
现在你可以在任何点 x
计算函数 f(x)
的值了。例如,print f(2.5)
会返回 x=2.5 时的插值结果。
17
下面我使用的是 Scipy,但是 NumPy 里也有相同的功能(polyval 和 polyfit)。因为 NumPy 是 Matplotlib 的一个依赖库,所以如果你没有安装 Scipy,也可以从 NumPy 中导入这两个函数。
import numpy as NP
from scipy import polyval, polyfit
from matplotlib import pyplot as PLT
n=10 # 10 data points
# make up some data
x = NP.linspace(0, 1, n)
y = 7*x**2 - 5*x + 3
# add some noise
noise = NP.random.normal(.5, .3, 10)
y += noise
# the shape of the data suggests a 2d polynomial, so begin there
# a, b, c are the polynomial coefficients: ax^2 + bx + c
a, b, c = polyfit(x, y, 2)
y_pred = polyval([a, b, c], x) # y_pred refers to predicted values of y
# how good is the fit?
# calculate MSE:
MSE = NP.sqrt( NP.sum((y_pred-y)**2)/10 )
# MSE = .2
# now use the model polynomial to generate y values based on x values outside
# the range of the original data:
x_out = NP.linspace(0, 2, 20) # choose 20 points, 10 in, 10 outside original range
y_pred = polyval([a, b, c], x_out)
# now plot the original data points and the polynomial fit through them
fig = PLT.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x, y, 'g.', x_out, y_pred, 'b-' )
PLT.show()