线性回归绘图的麻烦

发布于 2025-01-26 10:32:41 字数 1190 浏览 1 评论 0原文

嗨,所以我试图使用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文件是这样构造的

https://i.sstatic.net/4fnvk.jpg

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

https://i.sstatic.net/4FnVK.jpg

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文