Search code examples
r-markdownknitrrgl

rmarkdown::render does not render an rgl::plot3d figure (but Knit button does!)


Consider the following example:

       ---
       title: "Untitled"
       output:
         pdf_document: default
       ---

       ```{r, setup}
       Sys.setenv(CHROMOTE_CHROME = "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe")
       options(rgl.useNULL = TRUE)
       rgl::setupKnitr()
       ```

       Plot:

       ```{r, rgl = TRUE, dev = "png"}
       rgl::plot3d(rnorm(10), rnorm(10), rnorm(10))
       ```

Running rmarkdown::render("temp.Rmd", output_format = "pdf_document") produces a PDF with no figure. Even more interestingly, hitting the Knit button in RStudio produces a perfect PDF! (Which is quite strange itself; I was under the impression that the Knit button is exactly the same as the above call.)


Solution

  • Using rgl = TRUE works with the hook_rgl function, which is one of the older ways of handling rgl in knitr. It was always problematic, so recent releases have recommended other approaches instead.

    Using rgl::setupKnitr(autoprint = TRUE) is the easiest one. It approximates the behaviour of base plotting: minor updates to a plot won't appear, only the final version is shown. If you don't want that, then you can leave it with autoprint = FALSE, and explicitly include rglwidget() calls to get a plot to appear.

    The auto-printing isn't perfect, e.g. some packages that produce rgl plots don't produce output in a way that will trigger it. You can read more about this in the ?rgl::setupKnitr help topic.