Render ggplotly() in R Markdown github_document - r

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.

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

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.

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

R Markdown: plots within a loop going out of margin when typesetting to PDF

When typesetting an R Markdown document to PDF, if a function draws multiple plots, those plots often appear side-by-side, with only the first plot fully within the margins of the page.
Minimal R Markdown example:
---
title: "Example re plotting problem"
author: "Daniel E. Weeks"
date: "May 3, 2016"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Multiple plots within a loop
```{r}
plots <- function() {
plot(rnorm(100))
hist(rnorm(100))
}
for (i in 1:3) {
plots()
}
```
Here is a screenshot of page 2 of the generated PDF
which shows the problem. I have searched online, but haven't yet found a solution to this problem.
Thank you.
The plot hook solution proposed by user2554330 is simple and works well. So this code draws all the plots within the margins of the resulting PDF:
---
title: "Example re plotting problem"
author: "Daniel E. Weeks"
date: "May 3, 2016"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Multiple plots within a loop
```{r}
plots <- function() {
plot(rnorm(100))
hist(rnorm(100))
}
```
## Call plotting function
```{r}
my_plot_hook <- function(x, options)
paste("\n", knitr::hook_plot_tex(x, options), "\n")
knitr::knit_hooks$set(plot = my_plot_hook)
for (i in 1:3) {
plots()
}
```
The problem is that the generated .tex file has no spaces between the \includegraphics{} calls. LaTeX gives warnings about overfull hboxes, because the graphics aren't big enough to sit alone on a line, and are too big when it puts two on each line.
You can tell LaTeX (TeX really) to output the bad lines without putting two figures on each line by adding
\pretolerance=10000
in the text before the code chunk. You'll probably want to set it back to its default value
\pretolerance=100
after the code chunk, or LaTeX won't try hyphenation afterwards, and text can look really ugly.
Another way to fix this would be to force each figure to be in its own paragraph. You can do this by adding this code
my_plot_hook <- function(x, options)
paste("\n", knitr::hook_plot_tex(x, options), "\n")
knitr::knit_hooks$set(plot = my_plot_hook)
into a code chunk before you do your plotting. This puts a blank line
before and after each figure.

R markdown: Knitr: histogram dows not show when document titles are present

I have been battling with a curious problem and would appreciate if someone can help me. I am using the latest version of R Studio and packages.
---
title: "XYZ"
author: "ACB"
date: "Tuesday, October 21, 2014"
output: pdf_document
---
typing `r data(mtcars)`.
Some text
```{r}
mtcars$am <- as.factor(mtcars$am)
levels(mtcars$am) <-c("Automatic", "Manual")
```
Some text
```{r fig.align='center', fig.height=4}
hist(mtcars$mpg[mtcars$am=="Automatic"], breaks=12, main="mpg for automatic vehicles", xlab="mpg", xlim=c(10, 35))
```
If I Knit the above to PDF the histogram does not show; if the output is to HTML it works.
Thanks

Resources