X-Mas Tree with 10 Lines of R Code

Besides the many negative aspects of going through a pandemic, there are also certain positive ones like having time to write short blog posts like this.

This one picks up a topic that was intensively discussed a couple of years ago on Wolfram’s page: Namely that the damped sine wave

f(t) = t sin(t)

can be used to draw a Christmas tree. Throw in some 3D animation using the R package rgl and the tree begins to become virtual reality…

Here is our version using just ten lines of R code:

library(rgl)

t <- seq(0, 100, by = 0.7)^0.6
x <- t * c(sin(t), sin(t + pi))
y <- t * c(cos(t), cos(t + pi))
z <- -2 * c(t, t)
color <- rep(c("darkgreen", "gold"), each = length(t))

open3d(windowRect = c(100, 100, 600, 600), zoom = 0.9)
bg3d("black")
spheres3d(x, y, z, radius = 0.3, color = color)

# On screen (skip if export)
play3d(spin3d(axis = c(0, 0, 1), rpm = 4))

# Export (requires 3rd party tool "ImageMagick" resp. magick-package)
# movie3d(spin3d(axis = c(0, 0, 1), rpm = 4), duration = 30, dir = getwd())
Exported as gif using magick

Christian and me wish you a relaxing time over Christmas. Take care of the people you love and stay healthy and safe.

Code and animation can be found on github.


Posted

in

by

Tags:

Comments

3 responses to “X-Mas Tree with 10 Lines of R Code”

  1. susan hilsenbeck Avatar
    susan hilsenbeck

    Thanks for the christmas tree. Super cool.

    1. Michael Mayer Avatar

      Thanks! And (almost) fully sustainable compared to a real one.

  2. […] Michael Mayer has a festive post: […]

Leave a Reply

Your email address will not be published. Required fields are marked *