2017-03-07 58 views
2

我使用scipy.optimize.curve_fit()绘制了线性最小二乘拟合曲线。我的数据有一些与它相关的错误,我在绘制拟合曲线时添加了这些错误。在scipy上绘制曲线拟合线上的一个西格玛误差线

接下来,我想绘制两条虚线,代表这两条线之间的曲线拟合和阴影区域上的一个西格玛误差条。这是我到目前为止已经试过:

import sys 
import os 
import numpy 
import matplotlib.pyplot as plt 
from pylab import * 
import scipy.optimize as optimization 
from scipy.optimize import curve_fit 


xdata = numpy.array([-5.6, -5.6, -6.1, -5.0, -3.2, -6.4, -5.2, -4.5, -2.22, -3.30, -6.15]) 
ydata = numpy.array([-18.40, -17.63, -17.67, -16.80, -14.19, -18.21, -17.10, -17.90, -15.30, -18.90, -18.62]) 

# Initial guess. 
x0  = numpy.array([1.0, 1.0]) 
#data error 
sigma = numpy.array([0.16, 0.16, 0.16, 0.16, 0.16, 0.16, 0.16, 0.16, 0.22, 0.45, 0.35]) 
sigma1 = numpy.array([0.000001, 0.000001, 0.000001, 0.0000001, 0.0000001, 0.13, 0.22, 0.30, 0.00000001, 1.0, 0.05]) 

#def func(x, a, b, c): 
# return a + b*x + c*x*x 


def line(x, a, b): 
    return a * x + b 

#print optimization.curve_fit(line, xdata, ydata, x0, sigma) 

popt, pcov = curve_fit(line, xdata, ydata, sigma =sigma) 

print popt 

print "a =", popt[0], "+/-", pcov[0,0]**0.5 
print "b =", popt[1], "+/-", pcov[1,1]**0.5 

#1 sigma error ###################################################################################### 
sigma2 = numpy.array([1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0])   #make change 
popt1, pcov1 = curve_fit(line, xdata, ydata, sigma = sigma2)       #make change 

print popt1 

print "a1 =", popt1[0], "+/-", pcov1[0,0]**0.5 
print "b1 =", popt1[1], "+/-", pcov1[1,1]**0.5 
##################################################################################################### 

plt.errorbar(xdata, ydata, yerr=sigma, xerr= sigma1, fmt="none") 
plt.ylim(-11.5, -19.5) 
plt.xlim(-2, -7) 


xfine = np.linspace(-2.0, -7.0, 100) # define values to plot the function for 
plt.plot(xfine, line(xfine, popt[0], popt[1]), 'r-') 
plt.plot(xfine, line(xfine, popt1[0], popt1[1]), '--')         #make change 

plt.show() 

不过,我认为虚线画出我需要一个西格玛错误从我提供的外部数据和YDATA numpy的阵列,而不是从曲线拟合。我是否必须知道满足我的拟合曲线的坐标,然后制作第二个数组来制作一个西格玛误差拟合曲线?

enter image description here

回答

2

似乎你画两条完全不同的线路。

取而代之,您需要绘制三条线:第一条是没有任何更正的情况,另外两条线应该使用相同的参数ab,但带有增加或减少的sigma。您可以从pcov中获得的协方差矩阵中获得相应的sigma。所以你会有这样的东西:

y = line(xfine, popt[0], popt[1]) 
y1 = line(xfine, popt[0] + pcov[0,0]**0.5, popt[1] - pcov[1,1]**0.5) 
y2 = line(xfine, popt[0] - pcov[0,0]**0.5, popt[1] + pcov[1,1]**0.5) 

plt.plot(xfine, y, 'r-') 
plt.plot(xfine, y1, 'g--') 
plt.plot(xfine, y2, 'g--') 
plt.fill_between(xfine, y1, y2, facecolor="gray", alpha=0.15) 

fill_between阴影错误栏线之间的区域。

这是结果:

enter image description here

您可以将相同的技术为其他行,如果你想要的。