多项式拟合与对数对数图

时间:2012-09-27 14:20:38

标签: python matplotlib scipy

我有一个简单的问题就是在log-log范围内拟合直线。我的代码是,

data=loadtxt(filename)
xdata=data[:,0]
ydata=data[:,1]
polycoeffs = scipy.polyfit(xdata, ydata, 1)
yfit = scipy.polyval(polycoeffs, xdata)
pylab.plot(xdata, ydata, 'k.')
pylab.plot(xdata, yfit, 'r-')

现在我需要在对数刻度上绘制拟合线,所以我只需更改x和y轴,

ax.set_yscale('log')
ax.set_xscale('log')

然后它没有绘制正确的拟合线。那么如何更改拟合函数(以对数刻度)以便它可以在对数对数刻度上绘制拟合线?

2 个答案:

答案 0 :(得分:2)

编辑:

from scipy import polyfit
data = loadtxt("data.txt")
xdata,ydata = data[:,0],data[:,1]
xdata,ydata = zip(*sorted(zip(xdata,ydata))) # sorts the two lists after the xdata    

xd,yd = log10(xdata),log10(ydata)
polycoef = polyfit(xd, yd, 1)
yfit = 10**( polycoef[0]*xd+polycoef[1] )

plt.subplot(211)
plt.plot(xdata,ydata,'.k',xdata,yfit,'-r')
plt.subplot(212)
plt.loglog(xdata,ydata,'.k',xdata,yfit,'-r')
plt.show()

答案 1 :(得分:1)

你想要

log(y) = k log(x) + q,所以

y = exp(k log(x) + q) = exp(k log(x)) * exp(q) = exp(log(x^k)) * exp(q) = A x^k

您可以看到一个要求是y(0) = 0

从代码的角度来看,您只使用数据的x绘制拟合函数,可能最好添加点:

xfit = scipy.linspace(min(xdata), max(xdata), 50)
yfit = scipy.polyval(polycoeffs, xfit)
ax.plot(xfit, yfit, 'r-')