如何将R map中的Leaflet保存为png或jpg文件? [英] How to save Leaflet in R map as png or jpg file?

查看:461
本文介绍了如何将R map中的Leaflet保存为png或jpg文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Leaflet包在R中创建地图.它运行完美.我可以使用导出"简单地在R中导出地图,但是我需要从R中的脚本中导出地图.我的简单代码是:

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()

它可以工作,但是...输出的png文件为白色空白.

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

推荐答案

出现了一个非常不错的解决方法 PhantomJS 才能使以下代码正常工作.

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")

这是生成的图像.

现在 webshot 已在CRAN上正式发布,并且在 mapview 包中引入了mapshot,因此不再需要此手动解决方法.现在,代码就像这样:

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")

这篇关于如何将R map中的Leaflet保存为png或jpg文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆