How to embed an rgl snapshot in Rmarkdown package vignette - r

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

Related

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

Remove line break in Markdown output

I want to print the content of a data.table to a Markdown document out of R-Studio. However, the ouput is somewhat wider, so I decreased the font, as described here: Code chunk font size in Rmarkdown with knitr and latex
However, even when decreasing the font to tiny, the line break remains although there is plenty of space to have the columns adjacent. I wonder how this can be achieved.
---
title: "mwe"
output: pdf_document
---
```
{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(data.table)
dat <- data.table(id=1:5,num=31:35,text=c("a","b","c","d","here you can find some long text to artificially widen this text column and demonstrate the problem"))
```
Here is some text.
\tiny
```{r}
dat
```
dat[5]
Check ?options and look for the parameter width that controls the number of columns printed per line:
---
title: "mwe"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(data.table)
dat <- data.table(id=1:5,num=31:35,text=c("a","b","c","d","here you can find some long text to artificially widen this text column and demonstrate the problem"))
```
\tiny
```{r}
dat
```
```{r}
options(width = 120)
dat
```

Rayshader in Rmarkdown file?

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.

I can't seem to get code chunks in R to work (using LaTeX)

Using the following R script:
X = 2:10
summary(X)
I want to output only the results of the summary(X) command and omit the X = 2:10 part in my output in my LaTeX builder.
I've been trying for a few hours now using many different websites, but none of them seem to be working as intended.
Can anybody explain to me what I should include in both my R script and also my LaTeX input to make it work?
See the help page ?RweaveLatex; you're interested in
<<chunkid, echo = FALSE>>=
X = 2:10
summary(X)
#
In R Markdown, this works for me:
---
title: "Your latex"
author: "yourself"
date: "6/9/2018"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# your paper intro:
```{r, echo = TRUE, include = TRUE}
X = 2:10
summary(X)
```

why does kable not print when used within a function in rmarkdown

I have to repeat certain outputs in many rmarkdown reports and want to write a function to use for this.
Calling a function outputs plots ok when I knit the rmd file but not kable data frames.
For example
---
title: "Markdown example"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# Markdown example
```{r mtcars}
make_outputs <- function(){
knitr::kable(head(mtcars))
plot(mtcars$mpg, mtcars$cyl)
hist(mtcars$cyl)
}
make_outputs()
```
Displays the plots but not the kable table.
You can do this by using print to print the kable output, setting the results="asis" of the code chunk and then using kable_styling from package kableExtra.
This works for me:
```{r mtcars, results='asis'}
library(kableExtra)
library(knitr)
make_outputs <- function(){
print(kable_styling(kable(head(mtcars))))
plot(mtcars$mpg, mtcars$cyl)
hist(mtcars$cyl)
}
make_outputs()
```
Using a return statement with all objects in a list can help here, You can try recordPlot or plot from base R to solve your problem, By putting each of these plots in list, I managed to get the plots along with your table. Changed your code a bit in return statement to plot each of the plots along with tables like this.
Option1:
Using list in return with all the objects binded together without using lapply in function call
---
title: "Markdown example"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# Markdown example
```{r mtcars}
make_outputs <- function(){
return(list(hist(mtcars$cyl),
knitr::kable(head(mtcars)),
plot(mtcars$mpg, mtcars$cyl)))
}
make_outputs()
```
Another version (In case you don't want the code to print hist output to your html then you can use below function to suppress it.
make_outputs <- function(){
h1 <- plot(hist(mtcars$cyl, plot=FALSE))
h2 <- knitr::kable(head(mtcars))
h3 <- plot(mtcars$mpg, mtcars$cyl)
return(list(h1, h2, h3))
}
Option2:
Another (better version by using invisible function on lapply to suppress NULL printing, then using results='asis' option in the markdown settings as below gives a clean output than earlier.
---
title: "Markdown example"
output: html_document
---
knitr::opts_chunk$set(echo = FALSE)
knitr::opts_knit$set(root.dir= normalizePath('..'))
knitr::opts_chunk$set(error = FALSE)
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# Markdown example
```{r mtcars, results='asis'}
make_outputs <- function(){
return(list(plot(hist(mtcars$cyl, plot =FALSE)),
knitr::kable(head(mtcars)),
plot(mtcars$mpg, mtcars$cyl)))
}
invisible(lapply(make_outputs(), print))
```
This has given me a histogram, a scatter plot and a table in the knitted html document. Hope this helps, Not sure though if you wanted this way. Please let me know in case you wanted in any other way.
The problem seems to be related to knitr::kable incorrectly detecting the environment for the printing when it is embedded inside a function. This interferes with its ability to correctly figure out how to format. We can hack around this by placing the object to print in the top level environment before we print it.
---
title: "Markdown example"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
print_kable = function(x) {
print(kable_print_output <<- x)
cat('\n')
}
```
# Markdown example
```{r mtcars, results='asis'}
make_outputs <- function() {
print_kable(knitr::kable(head(mtcars)))
plot(mtcars$mpg, mtcars$cyl)
print_kable(knitr::kable(tail(mtcars)))
}
make_outputs()
```
I got something similar working by
moving the knitr::kable(head(mtcars)) inside a return() at the end of the function.
including results = 'asis'
e.g.
---
title: "Markdown example"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# Markdown example
```{r results = 'asis'}
make_outputs <- function(){
print(plot(mtcars$mpg, mtcars$cyl))
print(hist(mtcars$cyl))
return(knitr::kable(head(mtcars)))
}
make_outputs()
```
If you use ggplot for plots, you will need to wrap your plot inside print()

Resources