r - when knit rmd the html file does not show interactive leaflet maps

Viewed 1362

I'm trying to plot spatial data on interactive maps using "mapview" and "purrr". The maps are visible when using Rstudio in the .rmd but not when knitting the html. This way of presenting data in rmd is supported by "ggplot2", so I thought exporting maps in html would be useful.

Sample data:

library(mapview)
library(dplyr)
library(purrr)

df <- data.frame(lon = 1:9,
                 lat = 1:9,
                 id = c(rep(1,5), rep(2,4))) %>% 
      st_as_sf(coords = c("lon", "lat"), crs = 4326)

# split dataframe in multiple datasets (to produce multiple plots for each group of data)
df <- split(df, df$id)

When trying to plot in html with "purrr" and "mapview":

df %>% map(mapview)

The output in html:

enter image description here

The output in Rstudio (both maps are available): enter image description here

1 Answers

You can use htmltools::tagList(), see: How to render leaflet-maps in loops in RMDs with knitr

If you want to use the tidyverse:

---
title: "R Notebook"
output:
  html_document
---


```{r}
library('tidyverse')
library('sf')
library('mapview')
library('htmltools')

# create data set
df = data.frame(lon = 1:9,
                 lat = 1:9,
                 id = c(rep(1,5), rep(2,4))) %>% 
      st_as_sf(coords = c("lon", "lat"), crs = 4326)

# split dataframe in multiple datasets (to produce multiple plots for each group of data)
df = split(df, df$id)



# create maps
df_maps = df %>% 
  purrr::set_names() %>% 
  map(.x = .,
      .f = mapview) %>% 
  map(.x = ., slot, name = "map")

# add html headers
df_maps =
  imap(.x = df_maps,
       .f = function(x, y) {
        list(h4(paste("Subset:", y)),
             x)
      }) %>%
  flatten()

# for printing the maps
tagList(df_maps)
```
Related