1

我有一个简单的问题是在对数刻度上拟合一条直线。我的代码是,

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

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

4

2 回答 2

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()
于 2012-09-27T14:24:34.893 回答
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-')
于 2012-09-29T09:57:02.700 回答