如何绘制数据点和最佳拟合线之间的线?

How to plot lines between datapoints and the Line of best fit?

我想绘制线性回归数据点与最佳拟合线之间的线。希望在附加图像中创建灰线。

这是一个最小的工作示例。

综上所述,点是scatter,拟合线是用numpy.polyfit, and the vertical segments are a LineCollection计算的。

import numpy as np
import matplotlib.pyplot as plt

# random data
n = 100
np.random.seed(0)
X = np.random.uniform(0,10,size=n)

noise = np.random.normal(0,2,size=n)
Y = X*2+1+noise

# setting up plot
ax = plt.subplot()
ax.scatter(X, Y, c='r', zorder=2)

# computing and plotting fit line
a, b = np.polyfit(X, Y, 1)

xs = np.linspace(0,10)
ax.plot(xs, a*xs+b, c='k', lw=2)

# computing and plotting grey lines
from matplotlib import collections  as mc
lines = [[(i,j), (i,i*a+b)] for i,j in zip(X,Y)]
lc = mc.LineCollection(lines, colors='grey', linewidths=1, zorder=1)
ax.add_collection(lc)

输出: