3

When I render a Rayshader graphic, it pops open Xquartz on my mac, no problem, but what if I wanted to include it in my Rmarkdown document, it just shows the code, no graphic? I understand this is a heavy graphic intensive render, but looking for any tips. thanks, below is my code:

---
title: "rayshader"
author: "Daniel"
date: "6/16/2020"
output: 
  html_document:
  self_contained: yes
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```


```{r cars}
library(rayshader)

#Here, I load a map with the raster package.
loadzip = tempfile() 
download.file("https://tylermw.com/data/dem_01.tif.zip", loadzip)
localtif = raster::raster(unzip(loadzip, "dem_01.tif"))
unlink(loadzip)

#And convert it to a matrix:
elmat = raster_to_matrix(localtif)

elmat %>%
  sphere_shade(texture = "desert") %>%
  add_water(detect_water(elmat), color = "desert") %>%
  add_shadow(ray_shade(elmat, zscale = 3), 0.5) %>%
  add_shadow(ambient_shade(elmat), 0) %>%
  plot_3d(elmat, zscale = 10, fov = 0, theta = 135, zoom = 0.75, phi = 45, windowsize = c(1000, 800))
```
Daniel_j_iii
  • 3,041
  • 2
  • 11
  • 27

3 Answers3

4

From the package owner:

To embed the plot into an RMarkdown document, you need to call rgl::rglwidget() after bringing up your plot. If you're embedding multiple plots, you will also have to close to previous plot using rgl::rgl.close() before plotting the next one.

reference

Worked for me.

Oliver
  • 8,169
  • 3
  • 15
  • 37
Wade Hobbs
  • 41
  • 3
1

Try adding this to the end of your code:

Sys.sleep(0.2)
render_snapshot()
0

I am able to generate interactive .HTML files of rayshader's 3D renders through the following approach in an R Markdown, using RStudio:

title: "title"
author: "author"
date: "date"
output: html_document

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)

library(rayshader)
library(MetBrewer)
library(tidyverse)
library(rgl)

knitr::knit_hooks$set(webgl = hook_webgl)

The key to embedding the 3D render is on the hook_webgl() function in knitr. The issue is discussed in more length in this thread:

including a interactive 3D figure with knitr

, including a reference to the alternative writeWebGL() function.

PJV
  • 13
  • 2