W3School TIY Editor

  • W3School 在线教程
  • 改变方向
  • 暗黑模式
​x
 
# 三行配置使编译器支持绘图功能:
import sys
import matplotlib
matplotlib.use('Agg')
​
import matplotlib.pyplot as plt
from scipy import stats
​
# 原始数据点
x = [5,7,8,7,2,17,2,9,4,11,12,9,6]
y = [99,86,87,88,111,86,103,87,94,78,77,85,86]
​
# 线性回归分析:计算斜率、截距等统计量
slope, intercept, r, p, std_err = stats.linregress(x, y)
​
# 定义线性回归函数
def myfunc(x):
  return slope * x + intercept
​
# 生成回归线数据点
mymodel = list(map(myfunc, x))
​
# 绘制散点图和回归线
plt.scatter(x, y)
plt.plot(x, mymodel)
plt.show()
​
# 两行代码实现图形输出:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()