线性回归绘图的麻烦
嗨,所以我试图使用reg.fit函数来绘制饮食中发出的二氧化碳的图。该代码运行正常,但是绘制的图显示了图形右侧堆叠的所有Y值,因此我认为X值通过的方式存在问题。
这是我的代码,
data = pd.read_csv("food.csv")
plt.figure(figsize=[15, 10])
plt.rc('xtick', labelsize=3)
imp_mean = SimpleImputer(missing_values=np.nan, strategy='constant', fill_value=0)
x= data['Date'].values
x = pd.to_datetime(x, errors="coerce")
print(x)
x = x.values.astype("float64").reshape(-1,1)
y = data['TOTAL'].values
imputer = imp_mean.fit([y])
y = imputer.transform([y])
print(y)
y = y.reshape(-1,1)
reg = LinearRegression()
reg.fit(x,y)
print(f"The slope is {reg.coef_[0][0]} and the intercept is
{reg.intercept_[0]}")
predictions = reg.predict(x)
plt.scatter(x, y,c='black')
plt.plot(x, predictions, c='blue', linewidth=2)
plt.title("CO2eq emitted from diet")
plt.ylabel('CO2eq');
plt.xlabel('Date');
plt.show()
这是图
https://i.sstatic.net/xafuk.jpg.jpg
CSV文件是这样构造的
hi so im trying to use the reg.fit function to plot a graph of the co2 emitted from a diet. the code runs ok but the graph that is plotted shows all of the y values bunched up at the right side of the graph so I think theres an issue with the way the x values are being passed.
this is my code
data = pd.read_csv("food.csv")
plt.figure(figsize=[15, 10])
plt.rc('xtick', labelsize=3)
imp_mean = SimpleImputer(missing_values=np.nan, strategy='constant', fill_value=0)
x= data['Date'].values
x = pd.to_datetime(x, errors="coerce")
print(x)
x = x.values.astype("float64").reshape(-1,1)
y = data['TOTAL'].values
imputer = imp_mean.fit([y])
y = imputer.transform([y])
print(y)
y = y.reshape(-1,1)
reg = LinearRegression()
reg.fit(x,y)
print(f"The slope is {reg.coef_[0][0]} and the intercept is
{reg.intercept_[0]}")
predictions = reg.predict(x)
plt.scatter(x, y,c='black')
plt.plot(x, predictions, c='blue', linewidth=2)
plt.title("CO2eq emitted from diet")
plt.ylabel('CO2eq');
plt.xlabel('Date');
plt.show()
this is the graph
https://i.sstatic.net/XAFuK.jpg
the csv file is structured like this
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论