Exemple de comment calculer avec python le coefficient directeur et l'ordonnée à l'origine d'une droite connaissant deux points distincts (x1,y1) et (x2,y2):
x1 = 2.0y1 = 3.0x2 = 6.0y2 = 5.0a = (y2 - y1) / (x2 - x1)b = y1 - a * x1print('slope: ', a)print('intercept: ', b)
en définissant une fonction:
def slope_intercept(x1,y1,x2,y2):a = (y2 - y1) / (x2 - x1)b = y1 - a * x1return a,bprint(slope_intercept(x1,y1,x2,y2))
En utilisant une régression simple avec scipy:
from scipy.stats import linregressslope, intercept, r_value, p_value, std_err = linregress([x1,x2],[y1,y2])print(slope,intercept)
Tracer avec matplotlib:

import matplotlib.pyplot as pltimport numpy as npx = np.linspace(0, 8, 100)y = a * x + bplt.scatter([x1,x2],[y1,y2], color='gray')plt.plot(x,y,linestyle='--')plt.title("How to calculate the slope and intercept of a line using python ?", fontsize=10)plt.xlabel('x',fontsize=8)plt.ylabel('y',fontsize=8)plt.xlim(0,8)plt.ylim(0,8)plt.grid()plt.savefig("calculate_line_slope_and_intercept.png")plt.show()
Références
| Links | Site |
|---|---|
| Coefficient directeur d'une droite | euler.ac-versailles.fr |
| ython Slope (given two points find the slope) -answer works & doesn't work; | stackoverflow |
| numpy.interp | docs.scipy.org |
| Program to find slope of a line | geeksforgeeks |
| Adding an arbitrary line to a matplotlib plot in ipython notebook | stackoverflow |
