W3School TIY Editor

  • W3School 在线教程
  • 改变方向
  • 暗黑模式
​x
 
# 三行配置使编译器支持绘图功能:
import sys
import matplotlib
matplotlib.use('Agg')
​
import matplotlib.pyplot as plt
from scipy import stats
​
# 原始数据集:
x = [89,43,36,36,95,10,66,34,38,20,26,29,48,64,6,5,36,66,72,40]
y = [21,46,3,35,67,95,53,72,58,10,26,34,90,33,38,20,56,2,47,15]
​
# 执行线性回归分析
# 斜率,截距,相关系数,p 值,标准误差:
slope, intercept, r, p, std_err = stats.linregress(x, y)
​
# 定义线性回归函数:
def myfunc(x):
    return slope * x + intercept  # y = kx + b
​
# 生成回归线预测值:
mymodel = list(map(myfunc, x))
​
# 绘制散点图和回归线:
plt.scatter(x, y, label='原始数据')  # 原始数据点
plt.plot(x, mymodel, color='red', label='回归线')  # 回归直线
plt.legend()  # 显示图例
plt.show()
​
# 两行代码实现图形输出:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()