1. Including an interactive 3D `rgl` graphic in a html report with `knitr`

    2013-03-08
    Source

    I posted a question on StackOverflow: how to embed an interactive 3D figure created with the rgl package into an html report created with knitr ? The next day, Yihui Xie has posted a solution. He has updated knitr to include this possibility.

    The first example

    Below is the rendering of the example given by Yihui.

    library(rgl)
    knit_hooks$set(webgl = hook_webgl)
    
    x <- sort(rnorm(1000))
    y <- rnorm(1000)
    z <- rnorm(1000) + atan2(x, y)
    open3d()
    plot3d(x, y, z, col = rainbow(1000))
    

    rgl_firstexamplesnapshot
    You must enable Javascript to view this page properly.

    A real-life motivated example

    As a statistician consultant I sometimes have to write statistical reports about a response surface analysis. Wouldn't it be great to include an interactive response surface in a statistical report ? (At least, for fun --- I do not want to encourage an abusive practice of 3D visualization, even when it is interactive)

    Russell V. Lenth's rsm package provides convenient functions to draw the response surface fitted with the lm() funtion or the rsm() function, as shown in the vignette Surface Plots in the rsm Package. Below is the interactive rgl version of the first example of the vignette.

    library(rsm)
    swiss2.lm <- lm(Fertility ~ poly(Agriculture, Education, degree = 2), data = swiss)
    open3d()
    persp3d.lm(swiss2.lm, Education ~ Agriculture, zlab = "Fertility")
    

    rgl_persp3dlmsnapshot
    You must enable Javascript to view this page properly.

    I have obtained the function persp3d.lm() I used above from the persp.lm() function of the rsm package by replacing every occurence of a call to the persp() function (graphics package) with a call to the persp3d() function (rgl package). Thus this example is nothing but a default output whose aesthetics could be greatly improved with the possibilites of Adler & Murdoch's rgl package.