2010-11-28 29 views
5

Tengo 10 valores de xey en mi archivo.Extrapolación de los datos trazados usando matplotlib

¿Hay alguna manera de que pueda extrapolar el gráfico, es decir, convertirlo en una función continua y aumentar su rango para otros valores de x en matplotlib?

Incluso agradecería si alguien me puede decir si hay algún otro software que pueda usar. Básicamente quiero que estos 10 valores se aproximen a una función continua para que pueda conocer el valor y en algún punto aleatorio x.

Respuesta

12

debajo i uso Scipy, pero los mismos funciones (polyval y polyfit) también son en NumPy; NumPy es una dependencia de Matplotlib para que puedas importar esas dos funciones desde allí si no tienes instalado SciPy.

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() 

alt text

5

Si está utilizando SciPy (Scientific Python) puede probar scipy.interp1d. Vea el manual para un ejemplo.

De lo contrario, cualquier software de hoja de cálculo decente debería ser capaz de hacer interpolación spline y darle un buen gráfico suave.

Tenga cuidado con extrapolación, though. Si no tiene un buen modelo para sus datos, puede obtener datos completamente no relacionados al extrapolar fuera de su rango de entrada.

Ejemplo (EDIT):

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') 

Ahora puede calcular la función de f(x) en cualquier punto x. Por ejemplo, print f(2.5) devolverá el valor interpolado para x = 2.5.

Cuestiones relacionadas