我试图在散点图上绘制线性回归线。我研究了它(例如Linear regression with matplotlib / numpy),但我的暗示不起作用
x = [-6.0, -5.0, -10.0, -5.0, -8.0, -3.0, -6.0, -8.0, -8.0, 7.5, 8.0, 9.0, 10.0, 7.0, 5.0, 5.0, -8.0, 8.0, 7.0]
y = [-7.094043198985176, -6.1018562538660044, -15.511155265492038, -2.7131460277126984, -8.6127363078417609, -3.1575686002528163, -10.246242711042497, -6.4333658386991992, -16.167988119268013, 2.4709555610646134, 4.5492058088492948, 5.5896790992867942, 3.3824425476540005, -1.8140272426684692, -1.5975329456235758, 5.1403915611396904, -4.4469105070935955, 0.51211850576547091, 5.7059436876065952]
m,b = numpy.polyfit(x,y,1)
plt.plot(x, y, x, m*x+b)
plt.show()
返回:
Traceback (most recent call last):
File "test.py", line 464, in <module>
correlate(trainingSet,trainingSet.trainingTexts)
File "test.py", line 434, in correlate
plt.plot(x, y, x, m*x+b)
File "C:\Python27\lib\site-packages\matplotlib\pyplot.py", line 2458, in plot
ret = ax.plot(*args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 3848, in plot
for line in self._get_lines(*args, **kwargs):
File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 323, in _grab_ne
xt_args
for seg in self._plot_args(remaining, kwargs):
File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 300, in _plot_ar
gs
x, y = self._xy_from_xy(x, y)
File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 240, in _xy_from
_xy
raise ValueError("x and y must have same first dimension")
ValueError: x and y must have same first dimension
我检查过x
和y
长度是一样的,它们是(19)。我有什么想法吗?
答案 0 :(得分:6)
问题是x
是python list
,而不是numpy
array
,因此*
的工作方式与预期不符:
>>> m * x
[]
这是工作示例
plt.plot(x, y, x, numpy.array(x) * m +b)