3

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

adl
  • 1,390
  • 16
  • 36

1 Answers1

2

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)
```
cstepper
  • 181
  • 1
  • 5
  • When I run this only the first geometry plots in the rmarkdown output. The second plots extent is set to the 2nd geometry set but only the first set of points is plotted. Anyone have an idea how to fix this issue (same code as this answer)? – Chris May 06 '22 at 00:00
  • Fixed it. set fgb=FALSE – Chris May 06 '22 at 00:07