"""regresi_lengkap.py — fit garis tiga cara, evaluasi, lalu menggambar hasilnya."""

import numpy as np
import statistics
from scipy.stats import linregress
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

jam = [2, 3, 4, 5, 6, 7]
nilai = [65, 70, 75, 82, 86, 91]

m_std = statistics.linear_regression(jam, nilai)
m_sci = linregress(jam, nilai)
m_np = np.polyfit(jam, nilai, deg=1)

print(f"statistics.linear_regression : slope = {m_std.slope:.4f}, intercept = {m_std.intercept:.4f}")
print(f"scipy.stats.linregress       : slope = {m_sci.slope:.4f}, intercept = {m_sci.intercept:.4f}")
print(f"numpy.polyfit                : slope = {m_np[0]:.4f}, intercept = {m_np[1]:.4f}")

R2 = m_sci.rvalue ** 2
print(f"R2 = {R2:.4f}")
print(f"prediksi 5.5 jam = {m_std.intercept + m_std.slope * 5.5:.2f}")

plt.figure()
plt.scatter(jam, nilai, label="data siswa")
plt.plot(jam, m_std.intercept + m_std.slope * np.array(jam),
         color="red", label="garis regresi")
plt.xlabel("Jam belajar per hari")
plt.ylabel("Nilai ulangan")
plt.title("Regresi Nilai terhadap Jam Belajar")
plt.legend()
plt.savefig("regresi_belajar.png")
plt.close()
print("regresi_belajar.png tersimpan")
