在R中将传单图渲染为栅格? [英] render leaflet plots as raster in R?
问题描述
我意识到这在很大程度上违背了使用交互式 leaflet
地图的目的,但我正在写一本传统的纸质书,我想展示 leaflet
包如何对于 R 作品.我正在用 LaTeX 编写本书并使用 knitr
进行渲染.有没有办法将 leaflet
地图渲染为光栅图像,以便将其包含在本书中?
这是一个最小的例子:
库(传单)地图 <- 传单() %>%addTiles() %>%addMarkers(lng = -77.03673,纬度 = 38.89761)
现在,如果我尝试像这样的块:
<<>>=地图@
我收到此错误:
validateCssUnit(sizeInfo$width) 中的错误:maxwidth"不是有效的 CSS 单位(例如,100%"、400px"、自动")
尝试另存为 PNG 也不起作用:
<<>>=png(文件名=test.png")地图dev.off()@
map
不继承自 ggplot
,因此 ggsave
也不起作用.
有什么办法可以使这个工作吗?
最近有一个关于
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?
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.
这篇关于在R中将传单图渲染为栅格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!