render leaflet plots as raster in R?

走远了吗. 提交于 2019-12-01 20:07:11

问题


I realize that this largely defeats the purpose of using an interactive leaflet map, but I'm writing a traditional paper book and I want to show how the leaflet package for R works. I'm writing the book in LaTeX and rendering with knitr. Is there a way to have a leaflet map render as a raster image such that it could be included in this book?

Here is a minimal example:

library(leaflet)
map <- leaflet() %>%
  addTiles() %>%
  addMarkers(lng = -77.03673, lat = 38.89761)

Now if I try a chunk like:

<<>>=
map
@

I get this error:

Error in validateCssUnit(sizeInfo$width): "\maxwidth" is not a valid CSS unit
(e.g., "100%", "400px", "auto")

Trying to save as a PNG doesn't work either:

<<>>=
png(filename = "test.png")
map
dev.off()
@

map doesn't inherit from ggplot, so ggsave won't work either.

Is there any way to make this work?


回答1:


There has been a recent question on How to save Leaflet in RStudio map as png or jpg file?. If you don't mind installing PhantomJS, the code below should help you create static images from leaflet (or mapview) maps. The only thing left to do then is to not show the saveWidget and webshot code in your book and instead import and display the png file created therefrom.

## install 'webshot' package
library(devtools)
install_github("wch/webshot")

## load packages
library(leaflet)
library(htmlwidgets)
library(webshot)

## create map
m <- leaflet() %>%
  addTiles() %>%
  addMarkers(lng = -77.03673, lat = 38.89761)

## save html to png
saveWidget(m, "leaflet_map.html", selfcontained = FALSE)
webshot("leaflet_map.html", file = "leaflet_map.png",
        cliprect = "viewport")

## optionally display image when using knitr
# p <- knitr::include_graphics("leaflet_map.png")

And here is some LaTeX output for demonstration purposes. If anyone is interested, the complete .Rnw source file is available from GitHub.



来源:https://stackoverflow.com/questions/35527206/render-leaflet-plots-as-raster-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!