Calculating with python the slope and the intercept of a straight line from two points (x1,y1) and (x2,y2):
x1 = 2.0y1 = 3.0x2 = 6.0y2 = 5.0a = (y2 - y1) / (x2 - x1)b = y1 - a * x1print('slope: ', a)print('intercept: ', b)
Using a function
def slope_intercept(x1,y1,x2,y2):a = (y2 - y1) / (x2 - x1)b = y1 - a * x1return a,bprint(slope_intercept(x1,y1,x2,y2))
Using s simple regression with scipy:
from scipy.stats import linregressslope, intercept, r_value, p_value, std_err = linregress([x1,x2],[y1,y2])print(slope,intercept)
Plot with 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()
References
| 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 |
