# How to calculate the slope and the intercept of a straight line with python ?

Published: February 14, 2019

Calculating with python the slope and the intercept of a straight line from two points (x1,y1) and (x2,y2):

````x1 = 2.0`
`y1 = 3.0`

`x2 = 6.0`
`y2 = 5.0`

`a = (y2 - y1) / (x2 - x1)`
`b = y1 - a * x1`

`print('slope: ', a)`
`print('intercept: ', b)`
```

Using a function

````def slope_intercept(x1,y1,x2,y2):`
`    a = (y2 - y1) / (x2 - x1)`
`    b = y1 - a * x1     `
`    return a,b`

`print(slope_intercept(x1,y1,x2,y2))`
```

Using s simple regression with scipy:

````from scipy.stats import linregress`

`slope, intercept, r_value, p_value, std_err = linregress([x1,x2],[y1,y2])`
`print(slope,intercept)`
```

Plot with matplotlib:

````import matplotlib.pyplot as plt`
`import numpy as np`

`x = np.linspace(0, 8, 100)`
`y = a * x + b`

`plt.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()`
```

Image

of