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
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) 
open3d()
## 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


Ggplot2
Animation
Interactivity
3D
Caveats
Data art



❤️ 10 best R tricks ❤️

👋 After crafting hundreds of R charts over 12 years, I've distilled my top 10 tips and tricks. Receive them via email! One insight per day for the next 10 days! 🔥