Issue
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?
Solution
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()
Answered By - Pascal Bugnion
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.