fit a line of best fit to xy-coordinates in python

To fit a line of best fit to XY-coordinates in Python, you can use the numpy library to calculate the slope and intercept of the line and matplotlib library to visualize the line.

Here is an example code that demonstrates fitting a line of best fit:

main.py
import numpy as np
import matplotlib.pyplot as plt

# XY-coordinates
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# Fit a line of best fit
slope, intercept = np.polyfit(x, y, 1)

# Generate points on the line
line_of_best_fit = slope * np.array(x) + intercept

# Plot the original XY-coordinates and the line of best fit
plt.scatter(x, y, color='red', label='XY-coordinates')
plt.plot(x, line_of_best_fit, color='blue', label='Line of Best Fit')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Line of Best Fit')
plt.legend()
plt.show()
529 chars
22 lines

In this example, the numpy.polyfit function is used to calculate the slope and intercept of the line that best fits the XY-coordinates. The resulting line equation is then used to generate points along the line. Finally, the original XY-coordinates and the line of best fit are plotted using matplotlib.pyplot.scatter and matplotlib.pyplot.plot functions.

Note that numpy.polyfit can fit higher-degree polynomials as well by changing the degree parameter. For example, np.polyfit(x, y, 2) would fit a quadratic curve to the XY-coordinates instead of a line.

Hope this helps!

related categories

gistlibby LogSnag