Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fit a curve using matplotlib on loglog scale

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?

like image 903
Pradeep Avatar asked Sep 12 '13 09:09

Pradeep


People also ask

What is Loglog in Python?

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.


2 Answers

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)))
like image 124
RiGonz Avatar answered Sep 24 '22 02:09

RiGonz


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()
like image 44
Pascal Bugnion Avatar answered Sep 24 '22 02:09

Pascal Bugnion