27 lines
628 B
Python
27 lines
628 B
Python
import numpy as np
|
|
from scipy.stats import linregress
|
|
import matplotlib.pyplot as plt
|
|
|
|
# Generate some example data
|
|
x = np.array([1, 2, 3, 4, 5])
|
|
y = np.array([2.5, 3.5, 4.5, 5.5, 6.5])
|
|
|
|
# Perform linear regression
|
|
slope, intercept, r_value, p_value, std_err = linregress(x, y)
|
|
|
|
# Calculate R^2
|
|
r_squared = r_value**2
|
|
|
|
# Print the slope, intercept, and R^2
|
|
print("Slope:", slope)
|
|
print("Intercept:", intercept)
|
|
print("R^2:", r_squared)
|
|
|
|
# Plot the data and the linear fit
|
|
plt.scatter(x, y, label='Data')
|
|
plt.plot(x, slope * x + intercept, color='red', label='Linear Fit')
|
|
plt.xlabel('X')
|
|
plt.ylabel('Y')
|
|
plt.legend()
|
|
plt.show()
|