Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
516 views
in Technique[技术] by (71.8m points)

render leaflet plots as raster in R?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

LaTeX


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...