8

I have 4 leaflet objects: A, B, C, D. I would like to plot them in a 2 by 2 grid, but I have been having a difficult time trying to do this.

My initial thought was to use ggplot and facet_grid, but ggplot does not know how to deal with objects of class leaflet.

I would appreciate the help!

zx8754
  • 52,746
  • 12
  • 114
  • 209
John Smith
  • 393
  • 1
  • 6
  • 17
  • 1
    The leaflet output is a htmlwidget. I would recommend `shiny` or `flexdashboard` to create a grid. They both can handle that type of output. – troh Jul 18 '17 at 19:13
  • 1
    The `mapview` library has some functions to deal with this. [See the section in this webpage on syncing.](http://pierreroudier.github.io/teaching/20170626-Pedometrics/20170626-web-vis.html) – Andy W Jul 18 '17 at 19:30
  • Or see [this page](https://r-spatial.github.io/mapview/articles/articles/mapview_05-extras.html) for an example of multiple maps in a grid – TimSalabim Jul 18 '17 at 20:31

3 Answers3

11

Leaflets (or any other htmlwidgets) can be combined with htmltools::tagList.

In this case, a simple html table can handle the layout:

library(htmltools)

leaflet_grid <- 
  tagList(
    tags$table(width = "100%",
      tags$tr(
        tags$td(A),
        tags$td(B)
      ),
      tags$tr(
        tags$td(C),
        tags$td(D)
      )
    )
  )

You can put the leaflet_grid in knitr chunk directly or use

browsable(leaflet_grid)

to render it from the console.

Using Shiny fluid page layout

Example with shiny fluid page layout functions:

library(shiny)

leaflet_grid_2 <- fluidPage(
  fluidRow(
    column(6, A), column(6, B) 
  ),
  fluidRow(
    column(6, C), column(6, D) 
  )
)

Using leafsync

library(leafsync)

To synchronise zoom on all panels, use sync:

sync(A, B, C, D)

And latticeView will create panels without synchronising

latticeView(A, B, C, D)

(see https://r-spatial.github.io/mapview/articles/articles/mapview_05-extras.html)

hyman
  • 315
  • 3
  • 13
bergant
  • 7,122
  • 1
  • 20
  • 24
0

You may wish to pull out a static image of the 4x4 html output as above. For that you can use the webshot package:

webshot::webshot(html, directory_to_drop_png_of_html)

-1

There is a package called "patchwork" which might work out for you. Patchwork is an extension for ggplot so it should work well with your maps. You can arrange plots with simple "+" "/" commands.

see https://cran.r-project.org/web/packages/patchwork/vignettes/patchwork.html

R Kalia
  • 17
  • 2