Python 散点图拟合直线及R平方值计算
好的,以下是修改后的代码,用于绘制散点图的拟合直线,并计算R平方值:
import numpy as np
import matplotlib.pyplot as plt
# 生成随机散点数据
x = np.linspace(0, 10, 100)
y = 2 * x + np.random.randn(100)
# 绘制散点图
plt.scatter(x, y, label='Data Points')
# 使用numpy的polyfit函数拟合一次多项式曲线
coefficients = np.polyfit(x, y, 1)
fitted_line = np.polyval(coefficients, x)
# 计算R平方值
y_mean = np.mean(y)
ss_total = np.sum((y - y_mean) ** 2)
ss_residual = np.sum((y - np.polyval(coefficients, x)) ** 2)
r_squared = 1 - (ss_residual / ss_total)
# 绘制拟合曲线
plt.plot(x, fitted_line, color='red', label='Fitted Line')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Scatter Plot with Fitted Line')
plt.legend()
plt.grid(True)
plt.text(2, 25, f'R-squared: {r_squared:.4f}') # 显示R平方值
plt.show()
运行这段代码将绘制散点图的拟合直线,并在图表上方显示R平方值。
希望这对你有帮助!如果你还有其他问题,请随时提问。
原文地址: https://www.cveoy.top/t/topic/Rmh 著作权归作者所有。请勿转载和采集!