3

我制作了一张地图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))

派生多边形错误(数据,lng,lat,缺失(lng),缺失(lat),“addPolygons”):未找到多边形数据;请为 addPolygons 提供数据和/或 lng/lat 参数

谢谢

4

2 回答 2

15

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

data(World, metro)
metro$growth <- (metro$pop2020 - metro$pop2010) / (metro$pop2010 * 10) * 100

ttm()
tm_shape(metro) +
    tm_bubbles("pop2010", col = "growth", 
               border.col = "black", border.alpha = .5, 
               style="fixed", breaks=c(-Inf, seq(0, 6, by=2), Inf),
               palette="-RdYlBu", contrast=1, 
               title.size="Metro population", 
               title.col="Growth rate (%)", id="name", 
               popup.vars=c("Population (2010)"="pop2010", "Population (2020)"="pop2020", "Growth (%)"="growth"),
               popup.format=list(growth=list(digits=4)))

在此处输入图像描述

于 2017-02-11T20:25:07.457 回答
4

免责声明:黑客

我将首先警告这是一个 hack,但代码应该可以实现您的目标。也许,在tmaprepo 上提交问题以获取其他弹出选项。

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

带有格式化弹出窗口的地图屏幕截图

于 2017-01-31T15:17:30.687 回答