Skip to main content
 首页 » 编程设计

python之matplotlib 的线性回归线给出 ValueError

2025年05月04日19zhoujg

我正在尝试在散点图上绘制线性回归线。我已经研究过它(例如 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)。知道我做错了什么吗?

请您参考如下方法:

问题是 x 是一个 python list,而不是一个 numpy array,所以 * 工作方式与您预期的不同:

>>> m * x 
[] 

这是工作示例

plt.plot(x, y, x, numpy.array(x) * m +b)