使用tmap在形状上弹出

时间:2017-01-30 16:07:09

标签: r popup leaflet tmap

我已经使用tmap制作了一张无法leaflet的地图,以包含在闪亮的应用中。我大致有我想要的东西:一个基于SpatialPolygonsDataFrame的填充颜色的专题地图,当你点击地图时,弹出一个关于多边形的额外信息。我想在点击时更改弹出窗口以获得更好的布局。默认情况下,会显示数据集中的名称,但它实际上并不是用户友好的 这是一个可重复的例子。

library(tmap)
library(leaflet)

data(Europe)

tmap_mode("view")
carte <- tm_shape(Europe) +
  tm_borders(alpha = 0.5) +
  tm_fill(col = "well_being",
          id = "name",
          popup.vars = c("life_exp","well_being"))
tmap_leaflet(carte)

我试图将矢量命名为popup.vars = c("Life Expectancy" = "life_exp", "Well being" = "well_being),但这不起作用 我还尝试在调用leaflet::addPolygons时添加弹出窗口,但是收到错误消息。

carte2 <- tm_shape(Europe) +
  tm_borders(alpha = 0.5) +
  tm_fill(col = "well_being")

nom <- Europe$name

tmap_leaflet(carte2) %>% 
  addPolygons(layerId = nom,
    popup = paste0("<b>",~name,"</b><br/>Life Expectancy : ",
                           ~life_exp," <br/>Well being : ", ~well_being))
  

derivePolygons(data,lng,lat,missing(lng),missing(lat),“addPolygons”)出错:     未找到多边形数据;请为addPolygons提供数据和/或lng / lat参数

由于

2 个答案:

答案 0 :(得分:7)

在开发版本中,popup.vars的矢量名称现在用作标签。另外,我已经为每个图层功能添加了popup.format。您可以分别指定每个变量的数字格式。

'GET /home': { 
    view: 'home',
    locals: {
        layout: false
    }
}

enter image description here

答案 1 :(得分:3)

免责声明:Hack

我将首先警告这是一个黑客,但代码应该完成你的目标。也许,在tmap repo上提出其他弹出选项的问题。

library(tmap)

data(Europe)

carte2 <- tm_shape(Europe) +
  tm_borders(alpha = 0.5) +
  tm_fill(col = "well_being")

# this is a hack, since I do not see a clean mechanism to accomplish
# look at the leaflet map calls for addPolygons
leafmap <- tmap_leaflet(carte2)

# if you are ok using another package
# install.packages("listviewer")
# listviewer::jsonedit(leafmap$x$calls)

# if not then
str(leafmap$x$calls, max.level=2)

# addPolygons is the call we need to adjust
#  in this example it is the fourth call
str(leafmap$x$calls[[4]], max.level=2)
# the popups are the fifth element of the args
leafmap$x$calls[[4]]$args[[5]]
# adjust these how you like
leafmap$x$calls[[4]]$args[[5]] <- leaflet:::evalFormula(
  ~paste0(
    "<b>",name,"</b><br/>",
    "Life Expectancy : ", life_exp,
    " <br/>Well being : ", format(well_being, digits=4)
  ),
  data=Europe
)

# warned this is a hack

screenshot of map with formatted popup