How to Plot Line of Best Fit in Python

Published on Aug. 22, 2023, 12:16 p.m.

To plot a line of best fit in Python , you can use the polyfit() function from NumPy to calculate the slope and intercept of the line and then use Matplotlib to plot the line over the scatter plot of the data. Here’s an example:

import numpy as np
import matplotlib.pyplot as plt

# Define the data
x_data = np.array([1, 2, 3, 4, 5])
y_data = np.array([2.5, 3.5, 4.5, 5.5, 6.5])

# Calculate the slope and intercept of the line of best fit
slope, intercept = np.polyfit(x_data, y_data, 1)

# Create a scatter plot of the data
plt.scatter(x_data, y_data)

# Plot the line of best fit
plt.plot(x_data, slope * x_data + intercept, 'r')

# Add labels and title
plt.xlabel('x')
plt.ylabel('y')
plt.title('Line of Best Fit')

# Show the plot
plt.show()

In this example, we define the x and y data, calculate the slope and intercept of the line of best fit using polyfit(), plot the data using scatter(), plot the line using plot(), and add labels and a title to the graph. Finally, we show the plot using show().

Tags:

related content