I am plotting simple 2D graph using loglog function in python as follows:
plt.loglog(x,y,label='X vs Y');
X and Y are both lists of floating numbers of n
size.
I want to fit a line on the same graph. I tried numpy.polyfit , but I am getting nowhere.
How do you fit a line using polyfit if your graph is already in loglog scale?
Make a plot with log scaling on both the x and y axis. This is just a thin wrapper around plot which additionally changes both the x-axis and the y-axis to log scaling. All of the concepts and parameters of plot can be used here as well.
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)))
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With