R小册子中重叠多边形的标签

时间:2017-10-31 14:11:10

标签: r leaflet

我需要标记几个重叠的多边形,但只显示最大的多边形标签。但是,当我使用一些模拟数据进行测试时,标签显示正确。我仔细比较了两种情况下的数据,但找不到造成问题的区别。

以下是模拟重叠多边形的最小示例:

library(leaflet)
library(sp)

poly_a <- data.frame(lng = c(0, 0.5, 2, 3),
                     lat = c(0, 4, 4, 0))
poly_b <- data.frame(lng = c(1, 1.5, 1.8),
                     lat = c(2, 3, 2))
pgons = list(
  Polygons(list(Polygon(poly_a)), ID="1"),
  Polygons(list(Polygon(poly_b)), ID="2")
)
poly_dat <- data.frame(name = as.factor(c("a", "b")))
rownames(poly_dat) <- c("1", "2")

spgons = SpatialPolygons(pgons)
spgonsdf = SpatialPolygonsDataFrame(spgons, poly_dat, TRUE)

leaflet() %>% addPolygons(data = spgonsdf, label = ~name
                          #           ,
                          #           highlightOptions = highlightOptions(
                          # color = "red", weight = 2,bringToFront = TRUE)
)

它正常工作:

enter image description here

enter image description here

然而,它并没有处理我的数据。

https://github.com/rstudio/leaflet/files/1430888/Gabs.zip

您可以将拉链拖到this site并使用i按钮查看其标记正确

enter image description here enter image description here

library(rgdal)

# download Gabs.zip and extract files to Gabs folder
hr_shape_gabs <- readOGR(dsn = 'Gabs', layer = 'Gabs - OU anisotropic')
hr_shape_gabs_pro <- spTransform(hr_shape_gabs, 
                                 CRS("+proj=longlat +datum=WGS84 +no_defs"))
leaflet(hr_shape_gabs_pro) %>%
  addTiles() %>% 
  addPolygons(weight = 1, label = ~name)

仅显示最大的多边形标签:

enter image description here

enter image description here

两种情况下的数据都是SpatialPolygonsDataFrame,数据槽有正确的多边形名称。

2 个答案:

答案 0 :(得分:1)

更改hr_shape_gabs中多边形的顺序:位置3中的多边形应该是较小的多边形。

library(leaflet)
library(sp)
library(rgdal)
hr_shape_gabs <- readOGR(dsn = 'Gabs - OU anisotropic.shp', 
                         layer = 'Gabs - OU anisotropic')

# Change the position of the smaller and wider polygons
# Position 1 = wider polygon, position 3 = smaller polygon
pol3 <- hr_shape_gabs@polygons[[3]]
hr_shape_gabs@polygons[[3]] <- hr_shape_gabs@polygons[[1]]
hr_shape_gabs@polygons[[1]] <- pol3
hr_shape_gabs$name <- rev(hr_shape_gabs$name)

hr_shape_gabs_pro <- spTransform(hr_shape_gabs, 
                                 CRS("+proj=longlat +datum=WGS84 +no_defs"))
leaflet() %>%
  addTiles() %>% 
  addPolygons(data= hr_shape_gabs_pro, weight = 1, label = ~name)

enter image description here

答案 1 :(得分:0)

这是sf中基于this answer的许多层的可扩展解决方案。

该想法是通过减小尺寸来对多边形进行排序,以使最小的多边形绘制在最后

library(sf)
library(dplyr)

# calculate area of spatial polygons sf object
poly_df$area <- st_area(poly_df)
poly_df <- arrange(poly_df, -area)

# view with labels in leaflet to see that small polygons plot on top
leaflet(poly_df) %>% addTiles() %>% addPolygons(label = ~id)

抱歉,缺乏可重复性。这更多是一个概念答案。