Polynomial fitting with log log plot

白昼怎懂夜的黑 提交于 2019-12-11 06:46:47

问题


I have a simple problem to fit a straight line on log-log scale. My code is,

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

Now I need to plot fit line on log scale so I just change x and y axis,

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

then its not plotting correct fit line. So how can I change fit function (in log scale) so that it can plot fit line on log-log scale?


回答1:


EDIT:

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



回答2:


you want

log(y) = k log(x) + q, so

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

as you can see one requirement is y(0) = 0.

From the code point of view, you are plotting the fit function using only the x of the data, probably it is better to add points:

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


来源:https://stackoverflow.com/questions/12623571/polynomial-fitting-with-log-log-plot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!