2

I already developed the multiple regression equation and know the coefficients, and have used plotly to graph both a fitted surface and a scatter plot of my data. What I want to do now is take the regression model and fit it as a 3D plane with the scatter plot. I tried using the code from similar questions that have been asked, but have not had any luck getting it to work. See these below:

Add Regression Plane to 3d Scatter Plot in Plotly

Configuring Regression Plane added to 3d Scatter Plot in Plotly

Here is what I have so far:

data <-read_xlsx
x1 <- data$Temperature
x2 <- data$Days
fit <- lm(Release ~ poly(x1, 2, raw = TRUE) + poly(x2, 2, raw = TRUE), data = data)
summary(fit)
#Use the summary to obtain coefficients

library(plotly)
    x <- x1
    y <- x2
    z <- data$Release

fig <- plot_ly(data, x = ~x, y = ~y, z = ~z, color = ~z)
fig <- fig %>% layout(
    title = "CRF N Release Over Temperatures and Time",
    scene = list(
      xaxis = list(title = "Temperature (C)"),
      yaxis = list(title = "Time (Days)"),
      zaxis = list(title = "%N Release")

This all works great and produces a scatter plot (View Here: https://rpubs.com/jbhenry/799959). From here on is where the code just doesn't seem to work. I only got it to produce a 3D plane once, but it looked bizarre (View Here: https://rpubs.com/jbhenry/799963).

fit <- lm(Release ~ poly(x1, 2, raw = TRUE) + poly(x2, 2, raw = TRUE), data = data)

#Graph Resolution (more important for more complex shapes)
graph_reso <- 1

#Setup Axis
axis_x <- seq(min(data$Temperature), max(data$Temperature), by = graph_reso)
axis_y <- seq(min(data$Days), max(data$Days), by = graph_reso)

library(reshape2)

#Sample points
crf_lm_surface <- expand.grid(Temperature = axis_x, Days = axis_y,KEEP.OUT.ATTRS = F)
crf_lm_surface$release <- predict.lm(fit, newdata = crf_lm_surface)
crf_lm_surface <- acast(crf_lm_surface, Temperature ~ Days, value.var = "release") #y ~ x

fig <- add_trace(p = fig,
                       z = crf_lm_surface,
                       x = axis_x,
                       y = axis_y,
                       type = "surface")
fig

The regression plane should not look anything like what is produced by this code. Can anyone help me figure out where things are going wrong?

Josh Henry
  • 21
  • 1

0 Answers0