Bruce
Bruce

Reputation: 35233

How to find the slope of a graph

Here is my code:

import matplotlib.pyplot as plt
plt.loglog(length,time,'--')

where length and time are lists.

How do I find the linear fit slope of this graph?

Upvotes: 17

Views: 74878

Answers (2)

mah65
mah65

Reputation: 588

You need to take advantage of np.array to change your list to an array, then do the other calculations:

import matplotlib.pyplot as plt
import numpy as np

Fitting_Log = np.polyfit(np.array(np.log(length)), np.array(np.log(time)), 1)   
Slope_Log_Fitted = Fitting_Log[0]

Plot_Log = plt.plot(length, time, '--')
plt.xscale('log')
plt.yscale('log')
plt.show()

Upvotes: 0

unutbu
unutbu

Reputation: 879361

If you have matplotlib then you must also have numpy installed since it is a dependency. Therefore, you could use numpy.polyfit to find the slope:

import matplotlib.pyplot as plt
import numpy as np

length = np.random.random(10)
length.sort()
time = np.random.random(10)
time.sort()
slope, intercept = np.polyfit(np.log(length), np.log(time), 1)
print(slope)
plt.loglog(length, time, '--')
plt.show()

Upvotes: 33

Related Questions