Search code examples
rplot3d

Plot simplices in 3D in R


I have a list of points and a list of simplices. I would like to plot the simplices in 3D given their vertices. Essentially, I am looking for the equivalent of segment() in 3D.

Example

Pts<-matrix(c(0,0,0,1,0,0,0,1,0,0,0,1),ncol =3,byrow=TRUE)
Simplex<-c(1,2,3,4)

So, I am looking for a way to input Pts and Simplex and getting a plot of the tetrahedron.

I’ve tried searching but so far the only possibility seems to write out the functions for the linear spaces and plot those. Any tips will be highly appreciated.


Solution

  • With the 'rgl' package:

    library(rgl)
    
    vertices <- rbind(
      c(0, 0, 0),
      c(1, 0, 0),
      c(0, 1, 0),
      c(0, 0, 1)
    )
    
    faces <- combn(4,3)
    for(f in 1:4){
      triangles3d(rbind(
        vertices[faces[1,f],],
        vertices[faces[2,f],],
        vertices[faces[3,f],]
      ), color="red", alpha=0.4)
    }
    

    enter image description here

    You can add the edges and the vertices:

    # add edges as thin cylinders
    edges <- combn(4, 2)
    for(e in 1:6){
      shade3d(cylinder3d(rbind(vertices[edges[1,e],],vertices[edges[2,e],]), 
                         radius = 0.02, sides = 30), col="yellow")
    }
    # add vertices as small spheres
    spheres3d(vertices, radius= 0.03, color = "yellow")
    

    enter image description here