Reputation: 404
For studying purposes, I am trying to make a simple linear regression without external libs to calculate the slope and the intercept:
import matplotlib.pyplot as plt
x = [1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2]
y = [60, 62, 64, 66, 68, 70, 72, 74]
n = len(x)
sx = sum(x)
sy = sum(y)
sxy = sum([x[i] * y[i] for i in range(n)])
sx2 = sum([x[i] ** 2 for i in range(n)])
b = (n * sxy - sx * sy) / (n * sx2 - sx ** 2)
a = (sy / n) - b * (sx / n)
def predict_peso(altura):
return a + b * altura
altura_prev = 1.75
peso_prev = predict_peso(altura_prev)
plt.plot(altura_prev, peso_prev, marker="o", markeredgecolor="red",
markerfacecolor="green")
plt.scatter(x, y)
plt.show()
But when I try to draw the line using axline:
plt.axline(xy1=(0, a), slope=b, linestyle="--", color="k")
I got this result:
What can I do to fix that and draw the line properly?
Thanks in advance !
Upvotes: 0
Views: 97
Reputation: 3609
The line is drawn correctly, but since you stated an xy1 point, the plot automatically zooms out to show it. We can return the view to the previous one by storing and then retrieving the xlim
and ylim
. Add this block after your plt.show()
x0, x1 = plt.xlim()
y0, y1 = plt.ylim()
plt.axline(xy1=(0, a), slope=b, linestyle="--", color="k")
plt.xlim(x0, x1)
plt.ylim(y0, y1)
Upvotes: 1