how to plot an sklearn ols fit on a scatter plot? in python

To plot an sklearn OLS fit on a scatter plot, you can use the matplotlib library. Here is an example of how to do it in Python:

main.py
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

# Create some sample data
X = [[1], [2], [3], [4], [5]]
y = [2, 4, 6, 8, 10]

# Fit the linear regression model
model = LinearRegression()
model.fit(X, y)

# Make predictions
y_pred = model.predict(X)

# Plot the scatter plot
plt.scatter(X, y, color='blue', label='Actual Data')

# Plot the OLS fit line
plt.plot(X, y_pred, color='red', linewidth=2, label='OLS Fit')

# Add labels and legends
plt.xlabel('X')
plt.ylabel('y')
plt.legend()

# Show the plot
plt.show()
549 chars
28 lines

In this example, we first create some sample data for the scatter plot. We then fit a Linear Regression model on this data using scikit-learn's LinearRegression class. We make predictions using the fitted model and plot the scatter plot using plt.scatter. Finally, we plot the OLS fit line using plt.plot and add labels and legends to the plot.

gistlibby LogSnag