Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to find the slope of a graph drawn using matplotlib?

Tags:

python

Here is my code:

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

where length and time are lists.

How do I find the slope of this graph?

like image 271
Bruce Avatar asked Feb 11 '10 12:02

Bruce


People also ask

How do you find the slope on a graph in Python?

You can find the line's slope using the linregress() function if we define the x and y coordinates as arrays. The following code uses the linregress() method of the SciPy module to calculate the slope of a given line in Python.

How do you draw a slope in matplotlib?

Matplotlib: Graph/Plot a Straight Line The slope equation y=mx+c y = m x + c as we know it today is attributed to René Descartes (AD 1596-1650), Father of Analytic Geometry. The equation y=mx+c y = m x + c represents a straight line graphically, where m is its slope/gradient and c its intercept.


1 Answers

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()
like image 76
unutbu Avatar answered Sep 18 '22 12:09

unutbu