我有一个简单的问题可以在对数-对数刻度上拟合一条直线。我的代码是
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')
那么它没有绘制正确的拟合线。那么,如何更改拟合函数(以对数刻度),以便可以在对数-对数刻度上绘制拟合线?
最佳答案
编辑:
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()