How to insert saved Leaflet widget into Rmarkdown HTML output - r

I create a Leaflet widget and save it locally:
library(htmlwidgets)
library(leaflet)
library(sf)
shp = st_read("/path/to/some/shapefile.shp")
m = shp %>%
leaflet() %>%
addProviderTiles(providers$CartoDB.Positron) %>%
setView(lng = -70, lat = 40, zoom = 11)
saveWidget(m, "m.html")
Now I want to load this widget in a Rmarkdown chunk:
---
title: "Title"
author: "author"
date: "5/8/2020"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
etc etc etc
```{r}
function_that_loads_widget("m.html")
```
etc etc etc
I've tried htmltools::includeHTML() but that makes the entire HTML output one big widget. The text of the report is not displayed.
I realize I could put the the code that created the Leaflet widget directly in the Rmarkdown chunk, but I don't want to do that.

knitr::include_url() appears to be the solution. This works for my blogdown post.
```{r, out.width="100%"}
knitr::include_url("url_of_html", height="1080px")
```

Related

Rmarkdown and gt::caption placed at bottom of table/output?

this recently came up with the gt:: package but I also remember this from kableExtra as well iirc.
I'm trying to both use the packages title option but also RMarkdowns fig.cap.
Is there a way to enable both or do I have to work around it, for example with {{captioneer}} ?
edit: this question has been solved using gt::gt(caption = "xy")
Next: is it possible to place this caption at the bottom of the table?
Thanks!
---
title: "gt caption"
author: ""
date: "10 5 2022"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# Header
```{r, fig.cap="I also want this fig.cap", echo = FALSE}
tab <- gt::gt(pressure, caption = "xy")
tab <- gt::tab_header(tab,
title = gt::md(
"Title via tab_header"))
tab
```
You could replace the caption argument in gt() with gt::tab_footnote()
tab <- gt::gt(pressure)
tab <- gt::tab_footnote(tab, footnote = "xy")
tab <- gt::tab_header(tab,
title = gt::md(
"Title via tab_header"))
tab

Get highcharter animations to play in ioslides

Here is a mini example of a markdown document to make some slides
---
title: "Example"
author: "Hugh Warden"
date: "31/03/2022"
output:
ioslides_presentation:
theme: flatly
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r preload packages, message=FALSE, warning=FALSE}
library(highcharter)
```
## Hello
```{r, echo = TRUE}
print("Hello")
```
```{r highchart}
highchart() %>%
hc_xAxis(categories = month.abb) %>%
hc_add_series(name = "Tokyo", data = sample(1:12))
```
I knit these to HTML slides for a presentation I am doing.
Highcharts has a great animation of drawing the graph that appears on slide 2, however, it plays this animation when you open the HTML document not when you switch to that slide. Is there a way of making it so that the highchart only draws itself when you move to the slide it is on?
Many thanks!

how can I show my "ztable" when I use "knit to HTML" in R?

I am having a problem with my ztable,
I want to knit my Rmarkdown file to HTML but I cannot find a way to display the table I created with ztable:
z=ztable(loucaste) %>% makeHeatmap(palette = "Blues") %>% print(caption="Table 2.)
I tried to set
options(ztable.table="html")
and put this at the beginning as I read somewhere else
output: html_document
header-includes: \usepackage{colortbl}
but it doesn't work when I knit to HTML. My intention was to create a sort of formatting table similar to the ones made on excel and ztable looks like the only way.
Try this minimal Rmd. The key seems to be options(ztable.type = "html") and in the chunk that generates the table, r results='asis'
If that works for you, substitute your code in the appropriate place i.e. ztable(loucaste) %>% makeHeatmap(palette = "Blues") %>% print(caption="Table 2.).
---
title: "ztable"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(ztable)
library(magrittr)
options(ztable.type = "html")
```
## R Markdown
```{r results='asis'}
matrix(1:100, nrow = 10) %>%
as.data.frame() %>%
ztable() %>%
makeHeatmap() %>%
print(caption = "table 2")
```

How to render leaflet-maps in loops in RMDs with knitr

I am currently fighting trying to get knitr to render my leaflet maps, taken from a collection to appear correctly in a rendered RMD html-output. I'm already aware about some potential problems when looping throug collections and generating graphical output with RMD/knitr, but still I can't figure out, how to make my example work for leaflet-maps.
Reproducible working example (Test_1.Rmd):
---
title: "test1"
author: "phabee"
date: "22 Mai 2018"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Title 1
```{r, fig.show='asis', echo=FALSE, results='asis'}
for (i in 1:4) {
cat("### Plot Number ", i, "\n")
plot(1,1)
# use plot.new() here to force rendering of potential plot-duplicates
plot.new()
cat("\n\n")
}
```
The above example renders as expected (at least after adding plot.new(), which I've learned here from Freedomtowin). But when I try to do the same with leaflet-maps, it doesn't work at all. No single map is being rendered:
Reproducible failing example (Test_2.Rmd)
---
title: "test2"
author: "phabee"
date: "22 Mai 2018"
output: html_document
---
```{r setup, include=FALSE}
library(leaflet)
knitr::opts_chunk$set(echo = TRUE)
```
## Title 1
```{r, fig.show='asis', echo=FALSE, results='asis'}
for (i in 1:4) {
cat("### Map Number ", i, "\n")
leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")
cat("\n")
}
```
I would expect the second Rmd to render 4 times the same map, showing different titles ("Plot Number 1-4"). But the output doesn't render any map at all. The output looks as follows:
After inspecting the generated html-output the output, it can be seen that there is nothing rendered at all and it's not just a visibility-issue:
However, when I evaluate the leaflet-section within the 2nd Rmd directly by 'highlighting' the code and hitting ctrl-Enter, the map renders as expected:
I already tried to
convert the leaflet-statement to an assignment statement
introduce cat() or print() commands to force map-output
play around with additional newline-characters '\n' before and/or after the map output section
fiddle around with the 'asis' directives from fig.show or results
without any effect. Does anyone have a clue here?
You need to put things in a tagList, and have that list print from the chunk. This just uses default settings for fig.show and results; it also uses the htmltools::h3() function to turn the title into an HTML title directly, not using the Markdown ### marker. (You might want h2 or h4 instead.)
---
title: "test3"
output: html_document
---
```{r setup, include=FALSE}
library(leaflet)
library(htmltools)
knitr::opts_chunk$set(echo = TRUE)
```
## Title 1
```{r echo=FALSE}
html <- list()
for (i in 1:4) {
html <- c(html,
list(h3(paste0("Map Number ", i)),
leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")
)
)
}
tagList(html)
```

RMarkdown: bookdown with plotly

I'm using the bookdown package with RMarkdown to generate web-based book similar to this, likewise with the option to download a pdf-version of the book.
I've included plotly graphs in my "book" which work nicely in the html-version of the book. Being interactive, the button "build book" throws an error when including pdf output in the YAML-header.
Based on this description I've found a workaround with a regular RMarkdown File to create pdfs with plotly graphs outputs. A minimal solution (outside bookdown) looks like this:
---
title: "test"
output:
pdf_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(plotly)
Sys.setenv("plotly_username" = "username")
Sys.setenv("plotly_api_key" = "API")
```
```{r cars}
library(plotly)
p <- plot_ly(x = c(1,2,3,4), y = c(2,4,1,3), type = 'scatter', mode = 'lines')
plotly_IMAGE(p, format = "png", out_file = "output.png")
```
![Caption for the picture.](output.png)
Is there a way to include this solution within bookdown, so that the graphs are automagically interactive in the html output and static (png) in the pdf output?
Based on this blogpost I was able to come up with a solution. Note, this only works
with the "knitr" button (see this post for a workaround)
with an internet connection (1) and Plotly Account (2)
(1) See this link to export static images locally (which I didn't get to work since I failed installing PhantomJS)
(2) Plotly has a user Quota of currently 100 plots / grids per user per day
---
title: "test"
output:
html_document: default
pdf_document: default
word_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(plotly)
library(pander)
Sys.setenv("plotly_username" = "YOUR PLOTLY USERNAME")
Sys.setenv("plotly_api_key" = "API KEY")
output <- knitr::opts_knit$get("rmarkdown.pandoc.to") # html / latex / docx
```
```{r, results="asis"}
print(output)
p <- plot_ly(x = c(1,2,3,4), y = c(2,4,1,3), type = 'scatter', mode = 'lines')
filename <- "output.png"
if(output %in% c("latex","docx")){
plotly_IMAGE(p, format = "png", out_file = filename)
pandoc.image(filename)
} else if(output == "html"){
p
} else(print("No format defined for this output filetype"))
```

Resources