Set a curve using matplotlib in log scale

I am drawing a simple 2D plot using the loglog function in python as follows:

plt.loglog(x,y,label='X vs Y'); 

X and Y are both lists of floating numbers of size n .

I want to put a row on the same chart. I tried numpy.polyfit, but I get nothing.

How did you put a line using polyfit if your chart is already on a log scale?

+6
source share
1 answer

Numpy doesn't care what the axis of your matplotlib graph is.

I assume that you think log(y) is some polynomial function of log(x) and you want to find this polynomial? If so, run numpy.polyfit for the logarithms of your dataset:

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

Now poly is the polynomial in log(x) which returns log(y) . To get a match for predicting y values, you can define a function that simply exponentiates your polynomial:

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

Now you can plot your suitable line on your loglog chart:

 plt.loglog(x,yfit(x)) 

And show it like this

 plt.show() 
+14
source

Source: https://habr.com/ru/post/953690/


All Articles