53

I'm using Leaflet package to create maps in R. It works perfectly. I can export maps in R with simply Export, but I need to export maps from script in R. My simple code is:

png("test_png.png")
(m <- leaflet() %>% addTiles())
dev.off()

It works but... the output png file is white blank.

2
  • Thanx, but I was trying "print" and it doesn't works. The effect is the same: white image.
    – sms
    Jul 10, 2015 at 9:57
  • There's a reason it's not easy to do: Leaflet is a JavaScript library for building interactive maps for the web. If you want a static map, there are lots of R packages that make them. When you force it, you're almost always overriding someone's well-thought-out design choices, and will usually end up with a subpar product. Choose the right tool for the job.
    – alistaire
    Jan 8, 2016 at 10:40

1 Answer 1

88

This very nice workaround emerged in response to a question asked a little later here on SO. Note that you are required to install PhantomJS to get the following code to work.

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

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

## create map
m <- leaflet() %>% addTiles()

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

And here's the resulting image.

map


Update:

Now that webshot has been officially released on CRAN and with the introduction of mapshot in the mapview package, this manual workaround is no longer required. Now, the code simply goes like this:

library(mapview)

## 'leaflet' objects (image above)
m <- leaflet() %>% addTiles()
mapshot(m, file = "~/Rplot.png")

## 'mapview' objects (image below)
m2 <- mapview(breweries91)
mapshot(m2, file = "~/breweries.png")

breweries

1
  • 2
    I think that the webshot() function must still be used to store high resolution maps, despite the mapview package.
    – ra_bea_a
    Apr 12, 2021 at 7:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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