Building a 3D knot wiith R and rgl

This is an illustration of what is possible to do with R and the rgl library: a 3D knot.

3d Section 3d: warning

With the rgl package, you can make the image moove and zoom in an out. Find this image in the interactive mode here.

# Library rgl

#Choose the size of the image on the output (800,650 to have 800 x 600)
r3dDefaults$windowRect <- c(0,50, 800, 650) 
## glX
##   1
#If you want to put line on the background
#bg3d(sphere = TRUE, color = c("grey", "white"), lit = TRUE, back = "lines" ,lwd=2)

# This is to output a rgl plot in a rmarkdown document
# rgl::setupKnitr()

# plot
bg3d( col=rgb(0.2,0.8,0.5,0.8) )
theta <- seq(0, 2*pi, len = 50)
knot <- cylinder3d(
center = cbind(sin(theta) + 3*sin(2*theta), 2*sin(3*theta), cos(theta) - 2*cos(2*theta)),
e1 = cbind(cos(theta) + 4*cos(2*theta),6*cos(3*theta),sin(theta) + 4*sin(2*theta)),radius = 0.9,closed = TRUE)
shade3d(addNormals(subdivision3d(knot, depth = 2)), col = rgb(0.4,0.2,0.8,0.3))

# To display in an R Markdown document:
# rglwidget()

# save it as png
# snapshot3d( "~/Desktop/#20_portfolio_knot_3D.png", fmt="png")

# To save interactive plot to a file:
htmlwidgets::saveWidget(rglwidget(width = 500, height = 500), 
                        file = "HtmlWidget/3dknot.html",
                        libdir = "libs",
                        selfcontained = FALSE

Related chart types

Data art


This document is a work by Yan Holtz. Any feedback is highly encouraged. You can fill an issue on Github, drop me a message on Twitter, or send an email pasting with

Github Twitter