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

标签 python graph matplotlib

我怎样才能使用 matplotlib 做出这样的估计线。

Graph generated using excel

我有几个点,我使用以下代码使用 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()

示例结果:

enter image description here

关于python - 如何用线性回归绘制散点图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24942631/

相关文章:

python - 何时以及如何将 `slice(obj)` 用于非 -`int`/`None` 类型?

python - 如何使用带有信号的 Django 模型继承?

python - KalmanFilter 总是在第一时间预测 0,0

python - 如何使用 networkx 在图形中显示节点名称?

android - MPAndroidChart 已弃用的 setDrawCubic() 的替代品是什么?

javascript - 如何在SAPUI5的网络图的控制按钮上附加事件?

python - Matplotlib 不可见注释

python - 将多个函数应用于数组的每一行

python - 如何在 matplotlib 绘图中正确设置 cartopy geoaxes 中的投影和变换

python - 跨类变量以在 PyQt GUI 中缩放绘图