【问题标题】:How to plot a scatter plot with its linear regression?如何绘制带有线性回归的散点图?
【发布时间】:2014-09-16 12:50:26
【问题描述】:

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

谢谢,

【问题讨论】:

  • 你不应该用它自己的 scatter 命令绘制每一个点。这需要很长时间,如果您想拥有一个图例,您将拥有每个点的条目。你可以使用这个:x = [value[0] for value in samples]y = [value[1] for value in samples]

标签: python graph matplotlib


【解决方案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()

示例结果:

【讨论】:

  • 我想你只想要fit=polyfit(smp[0],smp[1],1),因为smp[0] 是数组,就像plt.scatter 中的第一个参数一样。或者只是做x=smp[0]; y=smp[1]
  • @Gabriel 不,根据 OP 的 for 循环,样本数组的格式为 [[x1, y1], [x2, y2], [x3, y3], ..]。所以首先对xy 进行排序(一种方法)似乎是必要的。
  • 对,我现在明白了。如果是这种情况,则期望 OP 图的图例中有多个项目,但现在意识到 OP 代码没有生成该图像。
猜你喜欢
  • 1970-01-01
  • 2020-03-07
  • 2021-11-26
  • 2021-01-28
  • 2019-10-22
  • 2021-02-24
  • 1970-01-01
  • 2012-06-27
  • 1970-01-01
相关资源
最近更新 更多