我想为用户添加功能,以导出Shiny中由Tmap生成的地图 。我了解tmap会将地图转换为传单,但不适用于mapview :: mapshot,因为许多答案都可以将 Leaflet 地图保存在Shiny中。
以下任何一项工作:
map_expr <- reactive({
tm_shape(water1) +
tm_fill(col = "darkblue") +
tm_shape(county_outlines) +
tm_borders(col = "black") +
tm_shape(herd_summary) +
tm_symbols(col = "green", size = "REACTORS", scale = 0.15, alpha = 0.7) +
tm_shape(water1) +
tm_fill(col = "darkblue")
})
observe({
output$map <- renderTmap({
map_expr()
})
})
output$downloadData <- downloadHandler(
filename = "test.png",
content = function(file) {
# mapshot(map_expr(), file = file, cliprect = "viewport")
# tmap_save(map_expr(), file = file)
tmapProxy("map", session, {}) %>%
mapview::mapshot(file = file)
}
)
答案 0 :(得分:2)
经过反复试验,我最终让它工作起来,并在此处包含了一个可重现的示例,如下所示:
library(shiny)
library(tmap)
library(mapview)
data("World")
pal <- leaflet::colorBin(palette = grDevices::heat.colors(20), domain = World$HPI)
ui <- fluidPage(
titlePanel("Tmap Example"),
sidebarLayout(
sidebarPanel(
downloadButton("downloadData")
),
mainPanel(
tmapOutput("map")
)
)
)
server <- function(input, output) {
map_expr <- reactive({
tm_shape(World) +
tm_polygons("HPI")
})
output$map <- renderTmap({
map_expr()
})
output$downloadData <- downloadHandler(
filename = "test.png",
content = function(file) {
mapview::mapshot(tmap_leaflet(map_expr()), file = file)
}
)
}
shinyApp(ui = ui, server = server)
因此必须将 tmap 表达式保存到一个对象中(我将它保存到一个名为 map_expr 的反应式对象中,因此在代码中的其他地方调用此对象时必须包含括号)。
使用mapview包中的mapshot函数,可以保存一个leaflet对象,tmap中有一个名为tamp_leaflet的函数,可以将tmap对象转换为leaflet对象。
首先在应用程序外部对其进行测试,以确保 mapshot 正常工作。为了让它工作,我必须安装包 webshot 并且必须安装 phantomJS 这可以通过以下功能完成: webshot::install_phantomjs()
希望这会有所帮助!
答案 1 :(得分:0)
library(tmap)
data("World")
# pal accepts a character vector of colours
tm_shape(World) +
tm_polygons("HPI", pal = c("#DC0032","#FFF5AC","#00B0F0"))
# You can also store the palette in pal,
# and then call pal(3) to return three colours
pal = grDevices::colorRampPalette(c("#DC0032","#FFF5AC","#00B0F0"))
tm_shape(World) +
tm_polygons("HPI", pal = pal(3))