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:
How can I add the regression line for the "fit" model in this plot. 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. 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:Or if you need a plotly: