I'm building some fairly complex maps with the leaflet package and I'd like to embed them in an rmarkdown document (specifically an ioslides_presentation .Rmd file).

Right now the code for the maps is in an .R script and it is subject to change as I tinker around with map aesthetics. I know I can cut and paste each map's code into the .Rmd presentation doc, but I want to avoid have to manually update the .Rmd file every time a change is made. I figure that if I can save the leaflet output and embed it in the presentation that will be much smoother.

I know that htmlwidgets::saveWidget allows me to save leaflet maps. But how can I embed these outputs in the .Rmd presentation?


Put your map codes in a separate Rmd file, and include it in your main file.



I ended up hosting the output of htmlwidget::saveWidget on a Github Pages project website. I embedded the html files in the ioslides presentation using an iframe, as demonstrated below:

<iframe  title="My Map" width="980" height="400" src="http://username.github.io/reponame/maps/my_map.html" frameborder="0" allowfullscreen></iframe>

This approach has advantages and disadvantages for my workflow. I like that I do not have to create separate .Rmd files for the leaflet functions because I want to keep all of my analysis and visualization code together in one script. That said, hosting and embedding the html files means I have to add a git push to the gh-pages branch whenever I tweak the maps.

I decided to leave @bhaskar-karambelkar's solution marked correct because it is more straightforward than my own.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.