Rayshader in Rmarkdown file? - r

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))
```

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.

Try adding this to the end of your code:
Sys.sleep(0.2)
render_snapshot()

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.

Related

How do I stop a chart from showing on R markdown?

Aims
I have got the ouput that I want i.e. an interactive tree map. Yet, the R Markdown output also shows the static tree map, which I do not want to include.
I also want to adjust the font size on the interactive chart. I know how to adjust the font sizes of the labels in the static diagram using "fontsize.labels", but this does not affect the interactive tree map.
Reprex
---
title: "Untitled"
date: "03/05/2021"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r pressure, echo=FALSE}
library(treemap)
library(d3treeR)
# dataset
group <- c(rep("group-1",4),rep("group-2",2),rep("group-3",3))
subgroup <- paste("subgroup" , c(1,2,3,4,1,2,1,2,3), sep="-")
value <- c(13,5,22,12,11,7,3,1,23)
data <- data.frame(group,subgroup,value)
# basic treemap
p <- treemap(data,
index=c("group","subgroup"),
vSize="value",
type="index",
palette = "Set2",
bg.labels=c("white"),
align.labels=list(
c("center", "center"),
c("right", "bottom")
)
)
# make it interactive ("rootname" becomes the title of the plot):
inter <- d3tree2( p , rootname = "General" )
inter
Output
How do I get rid of the top static tree map?
How do I increase the font size in the interactive tree map?
If you can only answer one of the questions, please do.

Assign figure caption to html widget (vtree package) in R markdown output

I need to implement a figure caption in a plot that is generated by the vtree package in R markdown. I learned that this is a htmlwidget and figure captions should now be possible for htmlwidgets used in R markdown with install.packages('webshot') and webshot::install_phantomjs() (reference: https://bookdown.org/yihui/bookdown/html-widgets.html#ref-R-DT.
But days after I am not really any step further. I did not find any example (show case) for this issue (fig.cap for htmlwidgets in R markdown in the net) so my hope is that someone out there can give me some help!
In my iris dataset example, in Fig. 1 the caption is not working in contrast to Fig. 2.
my iris set example RMD file:
YAML
---
title: "test"
author: "TJ"
date: "14 12 2020"
output: html_document
---
code chunk 1: load libraries and data
knitr::opts_chunk$set(echo = TRUE)
library(vtree)
library(webshot)
library(tidyverse)
attach(iris)
df <- iris %>%
select(Species) %>%
cbind(sapply(levels(.$Species), `==`, .$Species))
code chunk 2: Figure 1
{r fig1, echo=FALSE, fig.cap="Vtree plot"}
vtree(iris, "Species")
code chunk 3: Figure 2
{r fig2, echo=FALSE, fig.cap="Scatter plot iris dataset"}
plot(Sepal.Length, Sepal.Width, main="Scatterplot Example",
xlab="Sepal Length ", ylab="Sepal Width ", pch=19)
There is a workaround using the Magick package.You save the image as .png using grVizToPNG (make sure you comment this line out before you render your document or put it in a separate chunk with ยด{r eval = FALSE}, otherwise you will get an error during rendering:
```{r eval=FALSE, echo = FALSE}
myimage <- vtree(iris, "Species")
saveMyimage <- grVizToPNG(myimage, width=800)
```
Here you use the Magickpackage:
```{r magick, echo= FALSE}
MyimagePNG <- image_read("myimage.png")
image_annotate(MyimagePNG, "Vtree plot", size = 35, gravity = "southwest")
```

Render ggplotly() in R Markdown github_document

Interactive graphs created with ggplotly() go along nicely with html_document output in R Markdown, see eg. RMarkdown and ggplotly. For github_document output, however, the knitted HTML preview file does not show ggplotly() graphs.
I adopted the code from the linked SO post and only changed the output format in the header. Does anyone know how to render plotly graphs correctly with this kind of output? Or at least, if that is even possible?
---
title: "RmarkdownExample"
author: "fdetsch"
date: "April 16, 2020"
output: github_document
---
Here is the graph I generated.
```{r setup, message = FALSE, echo = FALSE, warning=FALSE}
# Require
library(plotly)
# Create
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
# Plot
g <- qplot(carat, price, data=dsamp, colour=clarity)
# Call
ggplotly(g)
```
For output: github_document, I found a workaround that renders ggplotly() graphs nicely using iframes. The trick is to export the plotly widget as HTML and subsequently embed it as iframe. In my opinion, the advantage over output: html_document with keep_md enabled is that the online .md file simply prints a link to the intermediary HTML file instead of the full widget code, making it much tidier.
---
title: "Render `ggplotly()` graphs in `github_document`"
author: "fdetsch"
date: "`r Sys.Date()`"
output: github_document
---
Here is the graph I generated.
```{r setup, message = FALSE, echo = FALSE, warning = FALSE}
# Require
library(plotly)
# Create
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
# Plot
g <- qplot(carat, price, data=dsamp, colour=clarity)
# Call
p <- ggplotly(g)
```
```{r include, echo = FALSE}
htmlwidgets::saveWidget(p, "index.html")
htmltools::tags$iframe(
src=file.path(getwd(), "index.html"),
width="100%",
height="600",
scrolling="no",
seamless="seamless",
frameBorder="0"
)
```
At least when opening the preview HTML in an external viewer, the interactive graph shows up. The RStudio (preview version 1.3.938) viewer currently fails to render the image.
There seem to be some problems with github_document, see here. My workaround: knit to html_document and save the resulting *.md-file.
So the YAML header is:
---
title: "RmarkdownExample"
author: "fdetsch"
date: "April 16, 2020"
output:
html_document:
keep_md: true
---
You can then use the md file to upload to github.

How to embed an rgl snapshot in Rmarkdown package vignette

I created an R vignette for my package. This vignette embed an interactive rgl figure with webGL.
---
title: "title"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{title}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
```r
rgl::plot3d(runif(10), runif(10), runif(10))
```
```{r, echo = FALSE}
rgl::plot3d(runif(10), runif(10), runif(10))
rgl::rglwidget()
```
It works perfectly well but is over-killed for my needs. A simple non interactive picture would be good enough. The problem of the webGL display is that it creates a big file (>1 Mb). Thus I have a NOTE on CRAN about directory size. Rather than arguing about this NOTE I would like to reduce the size of the html output using a regular picture.
rgl::plot3d(runif(10), runif(10), runif(10))
rgl::rgl.snapshot()
This obviously does not work.
You need to use the old hook_rgl method described in the knitr docs, and updated within rgl. For example, these chunks will insert a PNG figure:
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
rgl::setupKnitr()
```
```{r rgl=TRUE, dev='png'}
rgl::plot3d(runif(10), runif(10), runif(10))
```

R Markdown Presentation not loading/ rendering interactive Plotly chart

I am using Plotly with R to create a chart that will be rendered in a R Markdown Presentation With Ioslides, but instead of showing the demo chart from the website like the following:
It is rendering the steps like this:
My code is pretty simple:
---
title: "R Markdown Presentation & Plotly"
author: "Eduardo Almeida"
date: "February 19, 2017"
output: ioslides_presentation
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
## Interactive plot with Plotly
```{r}
library(plotly)
p <- plot_ly(economics, x = ~date, y = ~unemploy / pop)
```
As Karthik Arumugham pointed out you need to display the plot, either by entering p or not assigning plot_ly to variable but calling it directly.
I'd suggest to explicitly state the missing variables (type='scatter', mode='markers') instead of suppressing the output messages. In addition you could add {r, warning=F} to get rid of the
Error: attempt to use zero-length variable name
message.
---
title: "R Markdown Presentation & Plotly"
author: "Eduardo Almeida"
date: "February 19, 2017"
output: ioslides_presentation
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
## Interactive plot with Plotly
```{r, warning=F}
suppressPackageStartupMessages({library(plotly)})
library(plotly)
plot_ly(economics, x = ~date, y = ~unemploy / pop, type='scatter', mode='markers')
```

Resources