简体   繁体   English

使用 R 可视化多元线性回归

[英]Visualizing multiple linear regression using R

I am trying to fit and visualize a multiple linear regression model using four variables.我正在尝试使用四个变量来拟合和可视化多元线性回归 model。

fit <- lm(general_data$Bacterial.Contigs ~ general_data$Soil.Temperature + general_data$Time.point + general_data$Year)

Here, Time.point and Year are categorical variables, and others are numerical variables.这里,Time.point 和 Year 是分类变量,其他是数值变量。

I created a 3D plot using the following code.我使用以下代码创建了 3D plot。

library(plotly)

plot_ly(data = general_data, z = ~Bacterial.Contigs, x = ~Soil.Temperature, y = ~Time.point, color = ~Year, colors = c('#0C4B8E' ,'#BF382A'),opacity = 0.5) %>%
  add_markers( marker = list(size = 4))

And the plot looks like this: plot 看起来像这样:

在此处输入图像描述

How can I add the regression line for the "fit" model in this plot.如何在此 plot 中添加“适合”model 的回归线。 I would really appreciate any help.我真的很感激任何帮助。 Thanks谢谢

You fitted a model with only additive effects , meaning your categorical values only add or decrease your response variables, the slope will not change for the different categories.您安装的 model 仅具有加性效应,这意味着您的分类值只会增加或减少您的响应变量,不同类别的斜率不会改变。 It's not easy to visualize that on a 3D plot, I suggest you try ggplot2 .在 3D plot 上很难想象,我建议你试试ggplot2

An example with mtcars , you basically placed the fitted values back into the data frame and call a line for the fitted values:mtcars ,您基本上将拟合值放回数据框中,并为拟合值调用一行:

dat = mtcars
dat$am = factor(dat$am)
dat$vs = factor(dat$vs)

fit <- lm(mpg ~ disp + am + vs,data=dat)
dat$fitted= fitted(fit)

library(ggplo2)
g = ggplot(dat) + geom_point(aes(x=disp,y=mpg)) + 
geom_line(aes(x=disp,y = fitted)) + facet_grid(am~vs)
print(g)

在此处输入图像描述

Or if you need a plotly:或者,如果您需要 plotly:

library(plotly)
ggplotly(g)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM