Search code examples
rplot3d

R Project: Plot a 3d Mesh (grid) using Plot3D package


I'm trying to plot a 3d grid with cuboid elements (transparent using the Plot3D package of R, however I cannot find a good solution. Any suggestions? The objective is to add the 3D grid in a 3d scatterplot using the function scatter3D.

enter image description here


Solution

  • I wrote the following code which solves my problem. I used the function 'lines3D' of the Plot3D package. I'll appreciate it if you can provide a more elegant way to avoid the loops.

    library(plot3D)
    library(plot3Drgl)
    x_grid <- y_grid  <- seq(0 , 1000, 200)
    z_grid<-seq(0 , 500, 100)
    # plot a 3-D mesh
    
    M <- mesh(x_grid, y_grid, z_grid)
    # plot result
    
    dev.new()
    scatter3D(M$x, M$y, M$z, pch = "-", cex = 0.1, colkey = FALSE,ticktype = "detailed")
    
    for(i in 1:length(z_grid)){
    for(j in 1:length(y_grid)){
    lines3D(x = c(min(x_grid), max(x_grid)), y = c(y_grid[j],y_grid[j]), z = c(z_grid[i],z_grid[i]),colkey = FALSE,add=TRUE)}}
    
    for(i in 1:length(x_grid)){
    for(j in 1:length(y_grid)){
    lines3D(x = c(x_grid[i],x_grid[i]), y = c(y_grid[j],y_grid[j]), z = c(min(z_grid), max(z_grid)),colkey = FALSE,add=TRUE)}}
    
    for(i in 1:length(x_grid)){
    for(j in 1:length(z_grid)){
    lines3D(x = c(x_grid[i],x_grid[i]), y = c(min(y_grid), max(y_grid)), z = c(z_grid[j],z_grid[j]),colkey = FALSE,add=TRUE)}}
    
    plotrgl(new = TRUE)
    

    enter image description here