Visualizing multiple linear regression using R

465 views Asked by At

I am trying to fit and visualize a multiple linear regression model using four variables.

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.

I created a 3D plot using the following code.

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:

enter image description here

How can I add the regression line for the "fit" model in this plot. I would really appreciate any help. Thanks

1

There are 1 answers

0
StupidWolf On

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. It's not easy to visualize that on a 3D plot, I suggest you try ggplot2 .

An example with mtcars, you basically placed the fitted values back into the data frame and call a line for the fitted values:

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)

enter image description here

Or if you need a plotly:

library(plotly)
ggplotly(g)