简体   繁体   English

如何将R map中的Leaflet保存为png或jpg文件?

[英]How to save Leaflet in R map as png or jpg file?

I'm using Leaflet package to create maps in R. It works perfectly. 我正在使用Leaflet包在R中创建地图。它运行完美。 I can export maps in R with simply Export, but I need to export maps from script in R. My simple code is: 我可以使用“导出”简单地在R中导出地图,但是我需要从R中的脚本中导出地图。我的简单代码是:

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

It works but... the output png file is white blank. 它有效,但是...输出的png文件为白色空白。

This very nice workaround emerged in response to a question asked a little later here on SO. 这个很好的解决方法是针对稍后稍后在SO上提出的一个问题而出现的。 Note that you are required to install PhantomJS to get the following code to work. 请注意,您需要安装PhantomJS才能使以下代码正常工作。

## 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. 这是结果图像。

地图


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. 现在, Webshot已在CRAN上正式发布,并且在mapview软件包中引入了mapshot ,因此不再需要此手动解决方法。 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")

啤酒厂

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM