如何绘制带有线性回归的散点图?

3
我应该如何使用matplotlib制作类似于上图的估计线。
我有几个点,使用以下代码在matplotlib中对它们进行了绘制:
import matplotlib.pyplot as plt
for smp, lbl in zip(samples, labels):
    plt.scatter(smp[0], smp[1], marker='*', cl = 'b', s=100, label=lbl)

# set limit, xlabel, ylabel, legend ...
# ...

plt.show()

Thanks,


你不应该使用每个点配一个散点命令的方式来绘制图表。这样做很费时间,而且如果你想要添加图例,每个点都会有一个条目。 你可以使用以下代码:x = [value[0] for value in samples] y = [value[1] for value in samples] - MaxNoe
1个回答

1
使用polyfit进行线性回归:
import matplotlib.pyplot as plt
from pylab import polyfit, poly1d

x, y = zip(*samples)

fit = polyfit(x, y, 1)
fit_fn = poly1d(fit)
plt.plot(x,y, '*', x, fit_fn(x), 'k')

plt.show()

例子结果:

enter image description here


我认为你只是想要fit=polyfit(smp [0],smp [1],1),因为如果smp [0]plt.scatter中的第一个参数,则它就像一个数组。或者只需执行x=smp [0]; y=smp [1] - Gabriel
@Gabriel 不,根据原帖中的 for 循环,样本数组应该是这种格式 [[x1, y1], [x2, y2], [x3, y3], ..]。因此,首先对 xy 进行排序(无论哪种方式)似乎是必要的。 - dwitvliet
好的,我现在明白了。如果是那样,我本来期望 OP 图中图例有多个项目,但现在意识到原始代码并没有生成那张图片。 - Gabriel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接