Python 如何用线性回归绘制散点图?

Python 如何用线性回归绘制散点图?,python,graph,matplotlib,Python,Graph,Matplotlib,如何使用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.s

如何使用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()

谢谢,

使用
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()
示例结果:


我想您只需要
fit=polyfit(smp[0],smp[1],1)
作为
smp[0]
的数组,如果它是
plt.scatter
中的第一个参数。或者只做
x=smp[0];y=smp[1]
@Gabriel No,根据OP的
for
循环,样本数组的格式为
[[x1,y1],[x2,y2],[x3,y3],…]
。因此,首先排序
x
y
似乎是必要的(一种方式,另一种方式)。如果是这样的话,在OP plot的图例中应该有多个项目,但是现在意识到OP代码没有生成该图像。您不应该使用它自己的散布命令绘制每个点。这需要很长时间,如果你想有一个图例,你将有一个条目为每个点。您可以这样使用:
x=[value[0]表示样本中的值]
y=[value[1]表示样本中的值]