Fit a curve using matplotlib on loglog scale

Numpy doesn't care what the axes of your matplotlib graph are.

I presume that you think log(y) is some polynomial function of log(x), and you want to find that polynomial? If that is the case, then run numpy.polyfit on the logarithms of your data set:

import numpy as np
logx = np.log(x)
logy = np.log(y)
coeffs = np.polyfit(logx,logy,deg=3)
poly = np.poly1d(coeffs)

poly is now a polynomial in log(x) that returns log(y). To get the fit to predict y values, you can define a function that just exponentiates your polynomial:

yfit = lambda x: np.exp(poly(np.log(x)))

You can now plot your fitted line on your matplotlib loglog plot:

plt.loglog(x,yfit(x))

And show it like this

plt.show()

np.log(x) extracts the natural logarythm, so the fitting of the above solution is done on natural logs, while plt.loglog draws on 10-base logs.

Both operations should be run in the same base:

logx = np.log10(x)
logy = np.log10(y)

and

yfit = lambda x: np.power(10, poly(np.log(x)))

or

yfit = lambda x: 10**(poly(np.log(x)))