将传单图渲染为R中的栅格? [英] render leaflet plots as raster in R?

查看:94
本文介绍了将传单图渲染为R中的栅格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到这在很大程度上违反了使用交互式leaflet地图的目的,但是我正在写一本传统的纸质书,我想展示R的leaflet包的工作原理.我正在用LaTeX编写这本书,并使用knitr进行渲染.有没有一种方法可以将leaflet地图渲染为光栅图像,使其可以包含在本书中?

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?

这是一个最小的示例:

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

现在,如果我尝试像这样的块:

Now if I try a chunk like:

<<>>=
map
@

我收到此错误:

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

尝试另存为PNG也不起作用:

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

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

map不能从ggplot继承,因此ggsave也不起作用.

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

有什么办法可以使这项工作成功吗?

Is there any way to make this work?

推荐答案

最近在 PhantomJS ,则下面的代码应可帮助您从传单创建静态图像. strong>(或 mapview )地图.剩下要做的就是不在书中显示saveWidgetwebshot代码,而是导入并显示由此创建的png文件.

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

这是一些LaTeX输出,用于演示.如果有人感兴趣,可以从 GitHub .

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

这篇关于将传单图渲染为R中的栅格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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