model <- lm(mpg~ cyl+wt, data=mtcars)
b <- format(unname(coef(model)[1]), digits = 2)
m1 <- format(unname(coef(model)[2]), digits = 2)
m2 <- format(unname(coef(model)[3]), digits = 2)
rsquare <- format(summary(model)$r.squared, digits = 4)
#old technique doesn't work, as plotly cannot parse the equation like ggplot
#equation and r^2 is rewritten below to be put into the plot
eq = ("-1.5*Cylinders - 3.2*Weight + 40 ; r^2 = 0.830")
x = seq(4,8, by=0.2); y = seq(1,6, by=0.25) # Vectors of same length
Cylinders = matrix(rep(x,length(y)),nrow=length(x),byrow = T)
Wt = matrix(rep(y,length(x)),ncol=length(y),byrow = F) # Create mesh grids
MPG = Cylinders*coef(model)[2] + Wt*coef(model)[3] + coef(model)[1]
xax = list(title = "Cylinders");yax = list(title = "Weight (1000 lbs)")
zax = list(title = "MPG")
fig <- plot_ly(x=Cylinders, y=Wt, z=MPG, showscale = F) %>%
layout(scene = list(xaxis = xax, yaxis = yax, zaxis = zax))
fig <- fig %>% add_surface(z = MPG) #add plane
fig <- fig %>% add_trace(data = mtcars, x = mtcars$cyl, y = mtcars$wt, z = mtcars$mpg,
mode = "markers", type = "scatter3d", marker = list(size = 4, color = "red",
symbol = 10)) %>% # add data points
layout(title = 'MPG vs Weight vs Cylinders')
fig <- fig %>% add_annotations(x = 1.15, y = .9, z = 15, text = eq, showarrow = F) #label
fig