首页 > 解决方案 > plt.plot() 方法内部传递的参数是什么意思?

问题描述

我试图使用 scikit learn 和 matplotlib 在 python 中绘制线性回归模型。但是,当我使用 plt.scatter() 和 plt.plot() 绘制数据时,代码变得混乱

这是我的代码,它使用 sklearn 对数据进行建模:-

from sklearn import linear_model
regr = linear_model.LinearRegression()
train_x = np.asanyarray(train[['ENGINESIZE']])
train_y = np.asanyarray(train[['CO2EMISSIONS']])
regr.fit (train_x, train_y)
# The coefficients
print ('Coefficients: ', regr.coef_)
print ('Intercept: ',regr.intercept_)

这是我在图表上绘制线性回归模型的代码:-

plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS,  color='blue')
plt.plot(train_x, regr.coef_[0][0]*train_x + regr.intercept_[0], '-y')
plt.xlabel("Engine size")
plt.ylabel("Emission")

我不明白传入的参数plt.scatter()and plt.plot()。我注意到当我删除方法时plt.plot(),最佳拟合线没有绘制在图表上。

标签: pythonmatplotlibplotscikit-learn

解决方案


plt 库绘制数据。第一个条目是 x 数据,第二个条目是 y 数据。其他输入可用于添加颜色、线宽或标记类型,如文档中所示。

plt.scatter添加数据的散点图。我怀疑你的变量名称猜测:

plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS,  color='blue')

使用蓝色标记绘制所有发动机尺寸及其对应的二氧化碳排放量的散点图。

plt.plot画一条线。我怀疑你的变量名称猜测

plt.plot(train_x, regr.coef_[0][0]*train_x + regr.intercept_[0], '-y')

将以黄色绘制训练数据的线性回归。train_x是 x 数据和regr.coef_[0][0]*train_x + regr.intercept_[0]y 数据(它遵循公式 y = a*x + b)。


推荐阅读