Search code examples
r3dplotlyscatter-plotscatter3d

how to plot lines in 3d graph in R


I have these two 3d graphs made in R, with two different functions:

x <- c(0,50,100,150,200,250,300,350,400,450)
y <- c(0,50,100,150,200,250,300,350,400,450) 
z <- c(1,2,1,1,2,1,2,1,2,1)

plot_ly(x=x,y=y,z=z)
scatterplot3d(x, y, z)

I would like to plot in these two graphs, the following lines and the intersection area between them:

Lines plotted in both graphs

Lines plotted in both graphs


Solution

  • As per the lines and intersection with plotly, something like this will do:

    library(scatterplot3d)
    library(plotly)
    
    x <- c(0,50,100,150,200,250,300,350,400,450)
    y <- c(0,50,100,150,200,250,300,350,400,450) 
    z <- c(1,2,1,1,2,1,2,1,2,1)
    data <- data.frame(x=x,y=y,z=z)
    line <- data.frame(x = rep(200,5), y = seq(0,500,length.out = 5), z = rep(1,5))
    line2 <- data.frame(x = rep(300,5), y = seq(0,500,length.out = 5), z = rep(1,5))
    rect <- data.frame(expand.grid(x= c(200,300), y =c(200,300)),z = rep(1,4) )
    
    plot_ly() %>% 
    add_trace(data=data, x=x, y=y, z=z, type="scatter3d", mode="markers") %>% 
    add_trace(line, x = line$x, y = line$y, z = line$z, type = 'scatter3d', mode = 'lines', line = list(color = 'rgb(1, 1, 1)', width = 1 , dash = 'dash', width = 4))  %>% 
    add_trace(line2, x = line2$x, y = line2$y, z = line2$z, type = 'scatter3d', mode = 'lines',  line = list(color = 'rgb(1, 1, 1)', width = 1, dash = 'dash', width = 4))   %>% 
    add_trace(line, x = line$y, y = line$x, z = line$z, type = 'scatter3d', mode = 'lines', line = list(color = 'rgb(1, 1, 1)', width = 1 , dash = 'dash', width = 4))  %>% 
    add_trace(line2, x = line2$y, y = line2$x, z = line2$z, type = 'scatter3d', mode = 'lines',  line = list(color = 'rgb(1, 1, 1)', width = 1, dash = 'dash', width = 4))%>%  
    add_trace(rect,  x=rect$x, y=rect$y, z=rect$z, type="mesh3d" ) 
    

    Result with plotly:

    enter image description here