Setting a straight line to the log-log curve in matplotlib

I have a graph with me that is logarithmic on both axes. I have a pyplot function loglogto do this. It also gives me a logarithmic scale on both axes.

Now, using numpy, I map a straight line to the many points that I have. However, when I draw this line on the plot, I cannot get a straight line. I get a curved line. The blue line is the supposedly "straight line".  It is not getting plotted straight.  I want to fit a straight line to the curve plotted by red dots

The blue line is supposedly a "straight line". This is not straightforward. I want to put this straight line to the curve drawn by red dots

Here is the code I use to plot the points:

import numpy
from matplotlib import pyplot as plt
import math
fp=open("word-rank.txt","r")
a=[]
b=[]

for line in fp:
    string=line.strip().split()
    a.append(float(string[0]))
    b.append(float(string[1]))

coefficients=numpy.polyfit(b,a,1)
polynomial=numpy.poly1d(coefficients)
ys=polynomial(b)
print polynomial
plt.loglog(b,a,'ro')
plt.plot(b,ys)
plt.xlabel("Log (Rank of frequency)")
plt.ylabel("Log (Frequency)")
plt.title("Frequency vs frequency rank for words")
plt.show()
+4
source share
2 answers

, .

num b numpy,

a = numpy.asarray(a, dtype=float)
b = numpy.asarray(b, dtype=float)

. , -, , 10 a, b.

logA = numpy.log10(a)
logB = numpy.log10(b)

, . , logA, logB . , logA, logB.

coefficients = numpy.polyfit(logB, logA, 1)
polynomial = numpy.poly1d(coefficients)
ys = polynomial(b)
plt.plot(logB, logA)
plt.plot(b, ys)
+6

, ( polyfit, , ).


, (x, y), :

Linear regression diagram

, y x, . :

y = mx + b

m b, , .

y x. , x (think linspace) y. (x, y) .


. , y x, , y x. , y x , log(F) log(R). , .

Log regression diagram

. y x. , y x log(F) log(R) - .

- - , . ,

F = m R + b

, F R . ( -.)

log(F) = m log(R) + b

( 10 ),

F = c R^m

c = 10^b. F R: . ( -.)

A B polyfit, log(A) log(B).

+7

All Articles