Net_D
Net_D

Reputation: 33

r plotly not producing surface plot

I'm a complete newbie and would really appriciate your help!

Tried to create a surface 3D plot to plot an interaction, but it's not displaying the plot (when i'm doing a scatter3D plot, it does work). Used a data frame, where i want my x & y to be columns 1 and 2 and my z ( the predicted values of my y in my model) to be colunm 3.

Tried to separately define each axis, made no difference ):

df = data.frame(hobby = hobby,work = work, pred_well = predict.lm(m5.int)) 
plot(df)

plot_ly( df, type ="surface")

Upvotes: 1

Views: 1088

Answers (1)

Net_D
Net_D

Reputation: 33

eventually found a why for it to work, posting it, since i've seen many people are struggling with this

library(plotly) 
library(reshape2)

#Graph Resolution
graph_reso = 0.05

#Setup Axis
axis_x = seq(min(hobby), max(hobby), by = graph_reso)
axis_y = seq(min(work), max(work), by = graph_reso)

#Sample points
lm_surface = expand.grid(hobby = axis_x,work = axis_y,KEEP.OUT.ATTRS = F)
lm_surface$wellness = predict.lm(lm(wellness ~ work*hobby), newdata = lm_surface)
lm_surface = acast(lm_surface, work ~ hobby, value.var = "wellness") 

p_1  = plot_ly(myData, x = ~hobby, y = ~work, z = ~wellness, type = "scatter3d", mode = "markers" )%>% layout(title="Interaction Effect(Work Hours* Hobby Hours) on Wellness")

p_1 = add_trace(p = p_1,
                     z = lm_surface,
                     x = axis_x,
                     y = axis_y,
                     type = "surface")

Upvotes: 1

Related Questions