深度阅读

How to Plot Line of Best Fit in Python

作者
作者
2023年08月22日
更新时间
10.2 分钟
阅读时间
0
阅读量

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().

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。